Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 274
doc92606 Avatar asked May 30 '16 19:05

doc92606


People also ask

How does map function work in Swift?

Swift map function comes from the background of functional programming where the map reduces and filter the function with appropriate collections like arrays and dictionaries to loop over them without using any for loop.

What is array map in Swift?

Example 1: Swift Array map() This is a short-hand closure that multiplies each element of numbers by 3. $0 is the shortcut to mean the first parameter passed into the closure. Finally, we have stored the transformed elements in the result variable.

What does compact map Do Swift?

The compactMap(_:) function removes nil values from the input array. It's super useful when working with optionals.


1 Answers

You can use zip(_:_:) before map:

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

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

print(result) // => ["a1", "b2", "c3", "d4", "e5"]

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.

like image 97
Alexander Avatar answered Oct 26 '22 06:10

Alexander