Swift Language Arrays Transforming the elements of an Array with map(_:)


As Array conforms to SequenceType, we can use map(_:) to transform an array of A into an array of B using a closure of type (A) throws -> B.

For example, we could use it to transform an array of Ints into an array of Strings like so:

let numbers = [1, 2, 3, 4, 5]
let words = numbers.map { String($0) }
print(words) // ["1", "2", "3", "4", "5"]

map(_:) will iterate through the array, applying the given closure to each element. The result of that closure will be used to populate a new array with the transformed elements.

Since String has an initialiser that receives an Int we can also use this clearer syntax:

let words = numbers.map(String.init)

A map(_:) transform need not change the type of the array – for example, it could also be used to multiply an array of Ints by two:

let numbers = [1, 2, 3, 4, 5]
let numbersTimes2 = numbers.map {$0 * 2}
print(numbersTimes2) // [2, 4, 6, 8, 10]