typestar

Closures in Swift

Trailing braces and $0: the shape of everyday Swift.

let finishers = ["Sable", "Kestrel", "Petrel", "Brant"]

// A closure is a function literal; trailing syntax moves it out of
// the parentheses, and $0 names the first parameter.
let shouted = finishers.map { $0.uppercased() }
print(shouted)

let podium = finishers.sorted { $0.count < $1.count }
print("Shortest name first: \(podium)")

// Closures capture their surroundings.
var horn = 0
let sound = { horn += 1 }
sound(); sound()
print("Horn sounded \(horn) times")

How it works

  1. map { $0.uppercased() } is a closure outside the parens.
  2. sorted { $0.count < $1.count } compares with two positionals.
  3. Closures capture: sound increments the outer horn.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
469
Tokens
96
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 89 seconds.

Type this snippet

Step 2 of 3 in Functions & closures, step 8 of 27 in Language basics.

← Previous Next →

Closures in other languages