SwSwift
IntermediateLesson 10 of 16

Closures & Higher-Order Functions – Swift

Anonymous functions, map/filter/reduce, and capturing values.

A closure is a block of code that you can pass around like a value. The full syntax is { (parameter) -> ReturnType in code }; usually shorthand forms are enough: types are inferred, and $0, $1 are the parameters.

let zahlen = [1, 2, 3, 4, 5, 6]
let quadrate = zahlen.map { $0 * $0 }
let gerade = zahlen.filter { $0 % 2 == 0 }
let summe = zahlen.reduce(0, +)
let sortiert = ["Bob", "ada", "Cy"].sorted { $0.lowercased() < $1.lowercased() }
print(quadrate, gerade, summe, sortiert)
// [1, 4, 9, 16, 25, 36] [2, 4, 6] 21 ["ada", "Bob", "Cy"]

let verdopple = { (x: Int) -> Int in x * 2 }
print(verdopple(21))                                   // 42

If the closure is the last argument, you write it as a trailing closure after the parentheses. compactMap discards nil, flatMap flattens nested collections, and first(where:) and contains(where:) search.

func wiederhole(_ n: Int, aktion: () -> Void) {
    for _ in 0..<n { aktion() }
}
wiederhole(2) { print("Hi") }

print(["1", "x", "3"].compactMap { Int($0) })          // [1, 3]
print([[1, 2], [3]].flatMap { $0 })                    // [1, 2, 3]
print(zahlen.first(where: { $0 > 3 }) ?? 0)            // 4
print(zahlen.contains { $0 > 5 }, zahlen.allSatisfy { $0 > 0 })   // true true
print(Dictionary(grouping: zahlen, by: { $0 % 3 }).mapValues { $0.count })   // [0: 2, 1: 2, 2: 2] (order varies)

Closures capture variables from their environment and keep them alive. This is how counter functions arise, for example. Closures that outlive a function (storage, callbacks) must be @escaping.

func zaehlerMacher() -> () -> Int {
    var n = 0
    return {
        n += 1
        return n
    }
}
let z = zaehlerMacher()
print(z(), z(), z())                                   // 1 2 3

var handlers: [() -> Void] = []
func merke(_ h: @escaping () -> Void) { handlers.append(h) }
merke { print("A") }
merke { print("B") }
handlers.forEach { $0() }                              // A B
TipIn long closures, named parameters are more readable than $0. For map with a single function call, the shorthand zahlen.map(String.init) or map(\.name) with a key path also works.
WarningAn @escaping closure that captures the self of a class can create a retain cycle (object holds closure, closure holds object). Use a capture list then: { [weak self] in self?.aktualisiere() }.