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?
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.
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.
The compactMap(_:) function removes nil values from the input array. It's super useful when working with optionals.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With