Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

swift2

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
like image 716
Aidan Gomez Avatar asked Nov 13 '15 22:11

Aidan Gomez


People also ask

What does zip do Swift?

zip function is used to zip two sequencess in Swift. If you want to merge two arrays or any collection, the sequence then we can use the zip function for that. It will create a new sequence or collection of pairs that will contain elements from both the sequence or collection in Swift.


1 Answers

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)]
like image 99
Aidan Gomez Avatar answered Sep 21 '22 05:09

Aidan Gomez