Start learning free

LESSON 271 OF 678 · TUPLES, SORTING & BUILT-INS

Map and Filter in Swift

Lesson

TL ; DR:

The map method builds a new array with every item changed. The filter method builds a new array with only the items that pass a test. In the closure, $0 is the item.


let nums = [1, 2, 3, 4]

let squares = nums.map { $0 * $0 }                  // [1, 4, 9, 16]

let evens = nums.filter { $0 % 2 == 0 }             // [2, 4]

let big = nums.filter { $0 > 2 }.map { $0 * 10 }    // [30, 40]


Full lesson:

You often build a new array from an old one. You already know how to do it with a loop:

var squares = [Int]()
for n in nums {
    squares.append(n * n)
}

The map method does the same in one line. You give it a closure, as you gave sorted one in Closures and Sorting. It runs the closure on every item and collects the results in a new array.

let squares = nums.map { $0 * $0 }

$0 is the item. You can also give it a name: nums.map { n in n * n }.

filter takes a closure that gives true or false. It keeps only the items that get true.

let evens = nums.filter { $0 % 2 == 0 }

You can chain the two. First filter picks the items, then map changes them.

let big = nums.filter { $0 > 2 }.map { $0 * 10 }    // [30, 40]

Both return a new array. The old array, nums, stays as it was.

Watch out: the closure for filter must give true or false. { $0 > 2 } does. { $0 * 2 } doesn't compile there.


Your task

A theater keeps the price of one ticket for each show in prices. Build doubled with map: the price of two tickets for each show.

A quiz keeps its scores in scores. A score of 50 or more passes. Build passed with filter: only the passing scores.

The code already prints both arrays, one value per line.

Expected output:

Two tickets cost 24
Two tickets cost 16
Two tickets cost 30
72 passed
50 passed
90 passed
STEP 1 OF 2
    Ctrl + Enter to check