The latest experiment in the Swift Guided Tour asks the reader:
Change the function anyCommonElements (_: _ :) to make a function that returns an array of elements that have any two sequences in common.
My first quick jump on modification:
func anyCommonElements <T: SequenceType, U: SequenceType where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, _ rhs: U) -> [T.Generator.Element] { var commonElements = [T.Generator.Element]() for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { commonElements.append(lhsItem) } } } return commonElements }
I get an error related to my initializing the commonElements array in line 2 in Xcode 7.1.1:
Incorrect use of '[]' to call a value of non-functional type '[T.Generator.Element.Type]'
However, if I just change the initialization to use the longhand form to create an empty array in line 2, everything works fine and without errors:
func anyCommonElements <T: SequenceType, U: SequenceType where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, _ rhs: U) -> [T.Generator.Element] { var commonElements = Array<T.Generator.Element>() // Longhanded empty array for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { commonElements.append(lhsItem) } } } return commonElements }
The Swift documentation says:
The Swift array type is written completely as Array<Element> , where Element is the type of values that the array can be stored. You can also write the type of the array in abbreviated form as [Element] . Although the two forms are functionally identical, an abbreviated form is preferred and is used in this guide when it comes to array type.
(Emphasis added.)
If they are “functionally identical”, why do I get the error in the first example above, apparently only because I used the short form to create an empty array? Or maybe more likely - I lack a fundamental understanding of the problem?