Comparing 2 Arrays with zip
suggest changeThe zip function accepts 2 parameters of type Sequence 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)
numsAndAnimals now contains these pairs:
| First | Second |
|---|---|
| 1 | "Dog" |
| 2 | "Cat" |
| 3 | "Tiger" |
This is useful when you want to compare 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 in list1 is double the related value in list0.
filter receives one tuple, not two separate arguments (Swift 2 tuple splat no longer applies):
let list1HasDoubleOfList0 = zip(list0, list1).filter { pair in
pair.1 != 2 * pair.0
}.isEmpty
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents