Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 146 ยท Functions and Closures

map, filter, reduce and Friends

Learn Swift higher-order functions - map, compactMap, flatMap, filter, reduce, sorted, forEach and contains(where:) - with step-by-step examples, pitfalls and performance advice.

Almost every program loops over a collection to transform it, pick items from it or boil it down to one value. You can write those loops by hand, and sometimes you should. But Swift's standard library offers a small family of methods that express the three most common jobs directly: map transforms every element, filter keeps some elements, and reduce combines all elements into one value. They take a closure as their argument, which makes them higher-order functions.

The payoff is readability. A loop shows how to do something (make an empty array, iterate, append). A map call shows what you want ("the length of each word"). This lesson goes through each member of the family, shows the loop it replaces, and ends with the traps: laziness, performance and when a plain for loop is the better choice.

map: transform every element

map applies a closure to each element and returns a new array of the results, in the same order and with the same count. The result type can be different from the element type.

Swift map replaces a transforming loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

$0 is the shorthand name for the closure's first argument (see Closures). The array keeps its length: three prices in, three prices out. Notice the last lines: Optional has its own map, which transforms the value only when it is not nil. That is covered in Optionals in Depth.

map works on any Sequence, not only arrays. On a dictionary it gives you an array; use mapValues to keep a dictionary (see Dictionary Patterns).

filter: keep what passes a test

filter takes a closure that returns Bool and returns a new array with only the elements for which it returned true. Order is preserved.

Swift filter keeps matching elements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

An empty result is an empty array, never nil. Chaining is natural: filter then map reads as "keep these, then convert them."

reduce: combine into one value

reduce walks through the elements with a running result. You give it a starting value (the initial result) and a closure that takes the result so far and the next element and returns the new result. Think of it as the loop that keeps a running total.

Swift reduce builds one value from many

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Study the trace: the closure is called once per element. The first call receives your initial value 0, the following calls receive whatever the previous call returned. When the elements run out, the last result is returned.

The result of reduce can be a different type from the elements. Counting characters, building a string, or even building a dictionary are all fair jobs:

Swift reduce into a different type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

There are two forms. reduce(_:_:) returns a new value on every step. reduce(into:_:) hands your closure an inout accumulator that it changes in place. For arrays and dictionaries use the into: form: the plain form can copy the whole container on each step, which turns a linear job into a quadratic one.

compactMap: transform and drop nils

Parsing is a typical example: Int("42") returns Int?, because the text might not be a number. If you map over strings with Int(_:) you get [Int?]. compactMap does the same transformation, then throws away the nil results and unwraps the rest.

Swift compactMap removes nil results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Read compactMap as "map, and keep only the successes." Its older cousin, a version of flatMap that dropped nils, was renamed in Swift 4.1, so use compactMap for that job and nothing else.

flatMap: transform and flatten

flatMap takes a closure that returns a sequence for each element and joins all of them into one flat array.

Swift flatMap flattens one level

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

If map gives you an array of arrays ([[String]]), flatMap gives you the single flattened array. The last example builds all pairs (a, b) with a < b, a pattern that otherwise needs two nested loops.

sorted, min and max

sorted() returns a new array in ascending order (for Comparable elements). sorted(by:) takes a closure that says whether its first argument should come before the second. The closure must define a strict ordering: use <, not <=. Sorting and Searching Arrays goes deeper; here is the essential view.

Swift sorted, min and max with closures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Uppercase letters sort before lowercase in a plain sorted(), which is why "Mira" and "Alexander" come first. The tie-breaking closure for Player compares the score first, then the name, which makes the result predictable.

Searching and testing

A few more closure-based methods are worth knowing, because they stop early and are often faster than a full pass:

Swift first, contains and allSatisfy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

contains(where:), first(where:) and allSatisfy stop as soon as the answer is known. Notice that filter { ... }.first would test every element before looking at the first match; prefer first(where:).

forEach, and why it is not a loop

forEach calls a closure for every element. It looks like a loop but behaves differently in one important way: inside its closure, return only leaves that one call, and break and continue are not allowed.

Swift return inside forEach does not stop the loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

With forEach the return acts like continue: 3 is skipped but 4 and 5 are still processed. For ordinary iteration, prefer a for loop (Loops); it supports break, continue, labels and try/await without fuss. Use forEach for a quick one-liner with an existing function, like names.forEach(print).

Chaining and laziness

You can chain these methods into a pipeline. Each step creates an intermediate array, though, which costs memory for big data. Adding .lazy turns the chain into on-demand evaluation: elements flow one at a time through all the steps and no intermediate arrays are built. Lazy chains pay off when you only need the first few results (Lazy Sequences).

Swift Eager and lazy pipelines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The lazy version passes one number at a time through filter and then map, and it stops after looking at only the numbers 1 to 4. An eager chain would have processed all 20 numbers in every step before you could look at the first result.

A lazy sequence recomputes its closures every time you iterate it, and the closures run later than the line that writes them. Avoid side effects (such as print) inside lazy closures in real code; they appear here only to make the evaluation order visible.

Choosing between a loop and a higher-order function

Higher-order functions are not automatically better. A rough guide:

  • Use map, filter, reduce when one operation describes the whole job. They make the intent obvious and the result is a let constant, not a var you mutate.
  • Use a for loop when you need break, continue, return from the enclosing function, several outputs from one pass, or throwing and await inside the body.
  • Avoid long chains with complicated closures. If a closure needs more than three or four lines, give it a name (a local function) so the pipeline reads like a sentence.
  • Beware of chaining for performance-critical paths. Each eager step allocates an array. For hot code, one loop, or lazy, can be faster.
  • Do not use map for side effects. If you ignore the result, use for or forEach. The compiler warns about the unused result for good reason.
Swift Naming the steps of a pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Passing named functions (filter(isShipped)) keeps the pipeline short and the intent clear. The grouping at the end previews Dictionary Patterns.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does [1, 2, 3, 4].map { $0 * 2 } return?

    map applies the closure to every element and returns a new array with one result per element, in the same order.
  2. 2. You have let texts = ["7", "x", "9"]. Which call produces [7, 9]?

    Int(_:) returns an optional. compactMap keeps only the non-nil results and unwraps them, while map would give [Optional(7), nil, Optional(9)].
  3. 3. What is the value of [1, 2, 3].reduce(10) { $0 + $1 }?

    reduce starts with the initial value 10 and adds each element: 10 + 1 + 2 + 3 = 16.
  4. 4. Inside values.forEach { ... }, what does return do?

    The body of forEach is a closure, so return only leaves that closure call. The next element is still processed, and break and continue are not available.
  5. 5. Why prefer reduce(into:) over reduce(_:_:) when building a dictionary?

    With reduce(into:), the closure changes an inout accumulator. The plain form returns a new value per step, which can copy the whole container each time.

Summary

  • map transforms every element, filter keeps those that pass a test, reduce folds all elements into one value.
  • compactMap is map plus dropping nil; flatMap is map plus flattening one level of nesting.
  • sorted(by:) needs a strict "comes before" closure; min(by:), max(by:), first(where:), contains(where:) and allSatisfy finish early when they can.
  • reduce(into:) is the efficient choice for building arrays and dictionaries.
  • forEach is not a loop: return only skips one element and break is unavailable. Prefer for for control flow.
  • Eager chains build intermediate arrays; .lazy processes elements on demand, which helps when you need only a few results.
  • Name complex closures and choose a plain loop when it is clearer.

Next: Generic Functions