The zip
function accepts 2 parameters of type SequenceType
and returns a Zip2Sequence
where each element contains a value from the first sequence and one from the second sequence.
Example
let nums = [1, 2, 3]
let animals = ["Dog", "Cat", "Tiger"]
let numsAndAnimals = zip(nums, animals)
nomsAndAnimals now contains the following values
sequence1 | sequence1 |
---|---|
1 | "Dog" |
2 | "Cat" |
3 | "Tiger" |
This is useful when you want to perform some kind of comparation between the n-th element of each Array.
Example
Given 2 Arrays of Int(s)
let list0 = [0, 2, 4]
let list1 = [0, 4, 8]
you want to check whether each value into list1
is the double of the related value in list0
.
let list1HasDoubleOfList0 = !zip(list0, list1).filter { $0 != (2 * $1)}.isEmpty