Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Swift array syntax and Generic function

Since Xcode beta 3, we can write [int] as short hand for Array<Int>.

So we should write this:

func commonElements <T, U where T: Sequence, U: Sequence,
    T.GeneratorType.Element: Equatable,
    T.GeneratorType.Element == U.GeneratorType.Element>
    (lhs: T, rhs: U) -> [T.GeneratorType.Element] {
        var result = [T.GeneratorType.Element]()
        for lhsItem in lhs {
            for rhsItem in rhs {
                if lhsItem == rhsItem {
                    result += rhsItem
                }
            }
        }
        return result
}
commonElements([1, 2, 3, 4], [2, 4, 6])

For a reason I don't understand, Xcode doesn't accept the short syntax to initialize result array but accept its long equivalent Array<T.GeneratorType.Element>().

Am I missing something?

like image 408
clmntcrl Avatar asked Oct 20 '22 05:10

clmntcrl


1 Answers

Maybe the compiler is getting confused. This works though

var result: [T.GeneratorType.Element] = []

and is more readable IMO.

like image 81
JeremyP Avatar answered Oct 23 '22 02:10

JeremyP