Reputation: 9503
I stumbled into 'zip' in some code I'm studying.
So I looked it up to get the following:
zip(_:_:)
https://developer.apple.com/documentation/swift/1541125-zip
This is about as clear as milk.
What does zip do and when would you use it?
Upvotes: 1
Views: 276
Reputation: 8883
In addition to the given answers, I thought this would be helpful to add as an answer instead of a comment:
let a = [1, 2, 3]
let b = [1, 2, 3, 4, 5]
let c = Array(zip(a, b)) // [(1, 1), (2, 2), (3, 3)]
This is useful if you want to compare the two arrays with each other when you don't know the exact sizes of the arrays and the length is not an issue:
let d = zip(a, b).map { $0.0 + $0.1 } // [2, 4, 6]
Upvotes: 2
Reputation: 137438
Zip takes a pair of sequences, and turns them into a sequence of pairs.
So the two sequences:
A = 1, 2, 3
B = 4, 5, 6
Zipped become:
zip(A, B) = (1,4), (2,5), (3,6)
Upvotes: 7
Reputation: 1108
Consider two arrays, one of [Int]
and one of [String]
:
let a = [1, 2, 3]
let b = ["a", "b", "c"]
Then passing these two arrays to zip
will get you an array of pairs containing these elements in the same order:
let c = zip(a, b) // => [(1, "a"), (2, "b"), (3, "c")]
Upvotes: 2