Capturing Values
Capturing means a closure remembers and holds onto variables from where it was created, even after that place in the code has finished running.
Capturing a Variable
A closure automatically captures any variables it uses from its enclosing scope, keeping them alive and accessible even after that scope finishes.
Example: Capturing a Variable
func makeIncrementer(incrementAmount: Int) -> () -> Int {
var total = 0
let incrementer: () -> Int = {
total += incrementAmount
return total
}
return incrementer
}
let incrementByTwo = makeIncrementer(incrementAmount: 2)
print(incrementByTwo())
print(incrementByTwo())
print(incrementByTwo())
Login to try C/C++/Java/PHP code in the editor
Independent Captures per Closure Instance
Each call that creates a new closure gets its own independent captured storage, so separate closures don't interfere with each other.
Example: Independent Captures per Closure Instance
func makeIncrementer(incrementAmount: Int) -> () -> Int {
var total = 0
return {
total += incrementAmount
return total
}
}
let counterA = makeIncrementer(incrementAmount: 1)
let counterB = makeIncrementer(incrementAmount: 10)
print(counterA())
print(counterB())
print(counterA())
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Assuming a captured variable is copied at the moment of closure creation; in Swift, closures capture references and see later mutations.
- Being surprised that two closures created from the same function share the same captured variable's storage.
- Not realizing capturing a large object in a long-lived closure can keep it alive in memory longer than expected.
Chapter Summary
- A closure captures variables and constants from its surrounding context by reference.
- Because of capturing, a closure can still access and modify a variable after its original scope has ended.
- Multiple closures created in the same context can share the same captured variable.
- This capturing behavior is what makes closures useful for things like counters and callbacks.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: