doc92606 doc92606 - 1 year ago 38
iOS Question

Using "Map" in Swift To Create Superset of Two Arrays

Let's say I have two arrays:

let letterArray = ["a", "b", "c", "d", "e"...]
let numberArray = [1, 2, 3, 4, 5, 6, 7...]

I want to combine the two arrays so that I would get an output of

[a1, b2, c3, d4, e5]

How would I go about doing that?


You can't do this with map alone. You'll need to use zip(_:_:):

let a = ["a", "b", "c", "d", "e"]
let b = [1, 2, 3, 4, 5]

let result = zip(a, b).map{$0 + String($1)}


You can try this code here.

zip(_:_:) produces a custom Zip2Sequence, which has a special implmentation of the SequenceType protocol, so that it iterates pairs made from the two source collections.