Swift requires two generics of the same type

In 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 } 

T.GeneratorType.Element == U.GeneratorType.Element mean that the elements generated by the decomposition of the sequences have the same basic type. Therefore 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 must be sequences, such as String or Array.

How can I write a function that takes two parameters T and U, which must be of 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"

+6
source share
2 answers

As @conner noted, but you will never specify it that way, since there is only one type. This is better:

 func functionName<T> (lhs: T, rhs: T) -> Bool { ... } 
+5
source

If you want both of your parameters to be of the same type, you can use the same common to both of them. Sort of:

 func functionName <T, T> (lhs: T, rhs: T) -> Bool { return false } 
+1
source

Source: https://habr.com/ru/post/970409/


All Articles