Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift require that two generics are of the same type

Tags:

generics

swift

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"

like image 638
JuJoDi Avatar asked Jun 05 '14 20:06

JuJoDi


2 Answers

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 { ... }
like image 163
GoZoner Avatar answered Nov 09 '22 04:11

GoZoner


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
}
like image 25
Connor Avatar answered Nov 09 '22 03:11

Connor