Search code examples
swiftswift2

Swift: How does zip() handle two different sized collections?


The zip() function takes two sequences and returns a sequence of tuples following:

output[i] = (sequence1[i], sequence2[i])

However, the sequences can potentially be of different dimensions. My question is how does the Swift language deal with this?

The docs were utterly useless.

Seems to me, there are two possibilities (in Swift):

  • Stop at end of the shortest
  • Stop at end of longest, filling with default constructor or a predefined value for shorter's element type

Solution

  • Swift uses the first option, the resulting sequence will have a length equal to the shorter of the two inputs.

    For example:

    let a: [Int] = [1, 2, 3]
    let b: [Int] = [4, 5, 6, 7]
    
    let c: [(Int, Int)] = zip(a, b) // [(1, 4), (2, 5), (3, 6)]