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
map { $0.uppercased() }is a closure outside the parens.sorted { $0.count < $1.count }compares with two positionals.- Closures capture:
soundincrements the outerhorn.
Keywords and builtins used here
countletmapprintsortedvar
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.
Step 2 of 3 in Functions & closures, step 8 of 27 in Language basics.