In the Swift programming language I see an example
func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
It appears that T.GeneratorType.Element == U.GeneratorType.Element
means that the elements generated when the sequences are decomposed share the same underlying type. So I can do
anyCommonElements("123", "1234")
anyCommonElements([1, 2, 3], [1])
but not
anyCommonElements("123", [1, 2])
But T: Sequence, U: Sequence
means that the parameters T and U have to be sequences, such as a String or an Array.
What is the proper way to write a function that takes two parameters T and U which are required to be the same type using the where clause? Omitting the T: Sequence, U: Sequence
requirement results in the error "GeneratorType is not a member of type T"
As @conner noted but you would never specify it that way as there is only one type. This is better:
func functionName<T> (lhs: T, rhs: T) -> Bool { ... }
If you want both of your parameters to be the same type, you can just use the same generic for both of them. Something like:
func functionName <T, T> (lhs: T, rhs: T) -> Bool {
return false
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With