Skip to the workspace
Pebellslearn by building
Swift Basics  ›  Capstone Project

Functions and Closures

Swift Basics 12 minFunctions name reusable code with argument labels and default values, and closures are unnamed blocks of code passed to other functions such as sorted, filter and map.

ios / Functions and Closures

Explore each scene at your own pace.

01 · The rule

The rule

Functions and Closures

TrailLog shows total distance, the longest hike, and a list sorted by date. Each is a small piece of logic you want to name and reuse. Functions give logic a name; closures let you hand logic to someone else, like a sort.

The rule

A function is named reusable code; a closure is the same idea without a name.

A Swift function has argument labels that make calls read like sentences:

func totalDistance(of hikes: [Hike], inMiles: Bool = false) -> Double {
    let km = hikes.reduce(0) { $0 + $1.distanceKm }
    return inMiles ? km * 0.621 : km
}

totalDistance(of: journal)                 // default: kilometres
totalDistance(of: journal, inMiles: true)
  • of is the label used at the call site; hikes is the parameter name used inside.
  • _ as a label means "no label": func format(_ km: Double) is called format(8.5).
  • = false gives a default value, so the argument can be left out.
  • -> Double is the return type. No arrow means the function returns nothing.

A closure is a block of code you can store in a variable or pass as an argument. The full form is { (parameters) -> ReturnType in body }:

let byDate = journal.sorted(by: { (a: Hike, b: Hike) -> Bool in
    return a.date > b.date
})

Swift lets you trim that, step by step, because the types are already known from sorted(by:):

journal.sorted { a, b in a.date > b.date }   // types inferred, trailing closure
journal.sorted { $0.date > $1.date }         // shorthand argument names

When a closure is the last argument, it can go after the parentheses — a trailing closure. $0, $1 are shorthand names for the first and second parameters.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.