Capturing Values by Reference
Understand how closures capture surrounding state.
What Closures Capture
A closure captures the variables and constants from the surrounding scope that it references. Captured variables are held by reference, so the closure sees later changes.
Capturing a Constant
The closure remembers greeting even after the function returns:
func makeGreeter() -> () -> String {
let greeting = "Hello"
return { greeting }
}
let greet = makeGreeter()
print(greet()) // "Hello"All lessons in this course
- Capturing Values by Reference
- Escaping Closures
- Capture Lists and Weak Self
- Autoclosures