AnyCompiler

Closures

A closure is Swift's version of a lambda — a self-contained block of code that can be passed around as a value. Inside a trailing closure like { $0 % 2 == 0 }, $0 refers to the closure's first (here, only) parameter, letting you skip naming it entirely for short expressions.

let numbers = [1, 2, 3, 4, 5, 6]
let evenSquares = numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }
print(evenSquares)
Output
[4, 16, 36]

filter keeps only the elements where the closure returns true, and map transforms every element with the closure's result — chaining the two together reads almost like a description of the transformation itself: keep the even numbers, then square them.

Next: extensions — adding a method to a type you didn't write, without subclassing it.

Practice exercise

Given let numbers = [1, 2, 3, 4], use filter with a trailing closure to keep only even numbers, then map to square each one, and print the result.