Swift Closures
A closure is a block of code you can store in a variable and pass around — a function without a name. You use closures all the time in Swift: to sort arrays, to transform data, to react to a button tap in SwiftUI, or to run code when a network request finishes.
Closure syntax
The full form looks like this: parameters and return type come inside the braces, followed by the keyword in:
let greet = { (name: String) -> String in
return "Hi, \(name)!"
}
print(greet("Ama"))
let sayBye = {
print("Bye!")
}
sayBye()Hi, Ama!
Bye!
greet has the function type (String) -> String, exactly like a function declared with func.
Shortening closures step by step
When a closure is passed to a function, Swift can infer a lot, so you can write less. All five calls below do the same thing:
let names = ["Zoe", "adam", "Mia", "Ben"]
let a = names.sorted(by: { (s1: String, s2: String) -> Bool in
return s1.lowercased() < s2.lowercased()
})
let b = names.sorted(by: { s1, s2 in return s1.lowercased() < s2.lowercased() })
let c = names.sorted(by: { s1, s2 in s1.lowercased() < s2.lowercased() })
let d = names.sorted(by: { $0.lowercased() < $1.lowercased() })
let e = names.sorted { $0.lowercased() < $1.lowercased() }
print(a)
print(a == b && b == c && c == d && d == e)["adam", "Ben", "Mia", "Zoe"]
true
| Step | What was removed |
|---|---|
b |
types are inferred from sorted(by:) |
c |
single-expression closures return implicitly |
d |
shorthand argument names $0, $1, … |
e |
trailing closure: the last closure argument moves outside the parentheses |
Tip: Shorthand like
$0is great for one-liners. For longer closures, named parameters are easier to read.
Trailing closures
If a function's last parameter is a closure, you can write the closure after the call's parentheses — or drop the parentheses entirely if there are no other arguments. This is why SwiftUI code looks so clean:
func repeatTask(times: Int, task: (Int) -> Void) {
for i in 1...times {
task(i)
}
}
repeatTask(times: 3) { round in
print("Round \(round)")
}
let evens = [1, 2, 3, 4, 5, 6].filter { $0 % 2 == 0 }
print(evens)Round 1
Round 2
Round 3
[2, 4, 6]
Capturing values
A closure can capture variables from the surrounding code and keep using them — even after that code has finished. Each closure below keeps its own private count:
func makeCounter(step: Int) -> () -> Int {
var count = 0
return {
count += step
return count
}
}
let byOne = makeCounter(step: 1)
let byTen = makeCounter(step: 10)
print(byOne())
print(byOne())
print(byTen())
print(byOne())
print(byTen())1
2
10
3
20
The function makeCounter has returned long ago, but count lives on inside each closure. Closures are reference types: if you assign byOne to another constant, both names share the same counter.
Storing closures
Closures can live in arrays, dictionaries and properties. Here a small calculator looks up its operations by symbol:
let operations: [String: (Double, Double) -> Double] = [
"+": { $0 + $1 },
"-": { $0 - $1 },
"×": { $0 * $1 },
"÷": { $0 / $1 }
]
for symbol in ["+", "-", "×", "÷"] {
if let op = operations[symbol] {
print("12 \(symbol) 4 = \(op(12, 4))")
}
}12 + 4 = 16.0
12 - 4 = 8.0
12 × 4 = 48.0
12 ÷ 4 = 3.0
Escaping closures
If a function stores a closure to call it later (instead of calling it before returning), the parameter must be marked @escaping. This is common for callbacks:
var pendingHandlers: [() -> Void] = []
func onFinish(_ handler: @escaping () -> Void) {
pendingHandlers.append(handler) // stored for later → escaping
}
onFinish { print("Saving file…") }
onFinish { print("Showing 'Done' message") }
print("Handlers registered: \(pendingHandlers.count)")
for handler in pendingHandlers {
handler()
}Handlers registered: 2
Saving file…
Showing 'Done' message
Without @escaping the compiler reports an error, because it must know the closure may outlive the function call. Inside escaping closures in classes you'll often see [weak self] — that's covered in the Memory Management chapter.
Closures you'll meet everywhere
| Method | Closure job | Example |
|---|---|---|
sorted(by:) |
decide the order of two elements | scores.sorted { $0 > $1 } |
filter |
keep elements that return true |
nums.filter { $0 > 0 } |
map |
transform each element | names.map { $0.count } |
reduce |
combine everything into one value | nums.reduce(0) { $0 + $1 } |
forEach |
run code for each element | items.forEach { print($0) } |
You'll study map, filter and reduce in depth in the Higher-Order Functions chapter.
Test yourself
In the closure { $0 * 2 }, what is $0?
- The return value
- The first argument
- A global variable
- The closure itself
What is a trailing closure?
- A closure that runs last in the program
- A closure argument written after the function call's parentheses
- A closure with no parameters
- A closure marked @escaping
When must a closure parameter be marked @escaping?
- Always
- When the closure is stored and called after the function returns
- When the closure returns a value
- When the closure uses $0