5

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?

1 Answer 1

3

Maybe the compiler is getting confused. This works though

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

and is more readable IMO.

Sign up to request clarification or add additional context in comments.

2 Comments

I think it's a compiler bug, the next Xcode beta may solve it. (NB: [Type]() is the syntax Apple uses in its Swift doc to declare empty array.)
@clmntcrl Apple uses both notations []() appears 12 times in The Swift Programming Language and [] appears 7 times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.