Skip to the workspace
Pebellslearn by building
Core Programming Concepts  ›  Lesson

Functional Programming in Swift

Functional Programming 12 minSwift's map, filter and reduce transform, select and combine collection values through closures, favouring immutable data and pure functions over manual loops.

ios / Functional Programming in Swift

Explore each scene at your own pace.

01 · The rule

The rule

Functional Programming in Swift

TrailLog's statistics screen needs total distance, the names of long hikes, and the average elevation. You could write three loops with counters and temporary arrays. Or you can describe what you want and let Swift's collection functions do the looping.

The rule

Transform with map, keep with filter, combine with reduce.

These three higher-order functions take a closure and return a new value, leaving the original collection untouched:

let journal = [
    Hike(name: "Ridge Loop", distanceKm: 8.5),
    Hike(name: "Summit Push", distanceKm: 14.0),
    Hike(name: "River Walk", distanceKm: 3.0)
]

let names = journal.map { $0.name }
// ["Ridge Loop", "Summit Push", "River Walk"]

let long = journal.filter { $0.distanceKm > 5 }
// Ridge Loop and Summit Push

let total = journal.reduce(0) { sum, hike in sum + hike.distanceKm }
// 25.5
  • map — same number of items out as in, each transformed.
  • filter — fewer (or equal) items out, each unchanged, kept when the closure returns true.
  • reduce(initial, combine) — many items in, one value out. Start from initial and fold each item in.
  • compactMap — like map, but drops nil results: ["12", "x", "7"].compactMap { Int($0) } is [12, 7].

The functional style prefers immutable values (let) and pure functions — functions whose output depends only on their input and that change nothing else. Pure code is easy to test and safe to run from any thread.

These calls chain naturally, each step feeding the next:

let longNames = journal
    .filter { $0.distanceKm > 5 }
    .map { $0.name }
    .sorted()
// ["Ridge Loop", "Summit Push"]
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.