Reputation: 8627
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):
Upvotes: 11
Views: 3160
Reputation: 34993
Apple's zip(_:_:)
documentation has since been updated to answer this question:
https://developer.apple.com/documentation/swift/1541125-zip
If the two sequences passed to
zip(_:_:)
are different lengths, the resulting sequence is the same length as the shorter sequence. In this example, the resulting array is the same length aswords
:let words = ["one", "two", "three", "four"] let naturalNumbers = 1...Int.max let zipped = Array(zip(words, naturalNumbers)) // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)]
Upvotes: 0
Reputation: 8627
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)]
Upvotes: 15