Swift Functional Programming: map

January 3rd, 2018

Filed under: iOS Development, Mac Development | Be the first to comment!

The map function takes all the elements in a collection and applies a function or a closure (an unnamed function) to them. The following code demonstrates using map to multiply each element of an array by itself:

let numbers = [1, 2, 3, 4, 5]
let squares = numbers.map {
    return $0 * $0
}

The $0 expression represents the current item in the array.

The squares array has the following values:

[1, 4, 9, 16, 25]

You could double the items in the numbers array with the following code:

let doubles = numbers.map {
    return $0 * 2
}

Using map with a Named Function

I used closures in the previous examples. Now it’s time to demonstrate how to use map with a named function. Supply the name of the function as the argument to map. The following example uses a function with map to multiply each element of an array by itself:

func square(value: Int) -> Int {
    return value * value
}

let numbers = [1, 2, 3, 4, 5]
let squares = numbers.map(square)

Tags: ,


Leave a Reply

Your email address will not be published. Required fields are marked *