Creating an array of related type in Swift

I walk through the Guided Tour playground that comes with Swift 2.2. In the chapter on generics, you get this unusually bulky function declaration dumped on you:

func anyCommonElements <T: SequenceType, U: SequenceType where
    T.Generator.Element: Equatable,
    T.Generator.Element == U.Generator.Element>
    (lhs: T, _ rhs: U) -> Bool {

  for lhsItem in lhs {
      for rhsItem in rhs {
          if lhsItem == rhsItem {
              return true
          }
      }
  }
 return false

}
anyCommonElements([1, 2, 3], [3])

The function returns whether the two sequences have any common elements, which is quite simple.

The exercise for this chapter is changing a function to return an array of common elements between two sequences. From this, I get that the function should have a return type, e.g.

(lhs: T, _ rhs: U) -> [T.Generator.Element]

Which seems simple enough, create an array and put common elements in it, and then return it. But nothing in the book so far has taught me how to create a new type array [T.Generator.Element], so I don’t know how to do it. I naturally suggested that this works:

var result = [T.Generator.Element]()

, . , ? ( ?)

+4
1

, . Swift. :

  • var result: [T.Generator.Element] = []

  • var result = [] as [T.Generator.Element]

  • var result = Array<T.Generator.Element>()

( , , , . [T.Generator.Element]() .)

+1

All Articles