Capturing values from context lets a small piece of code remember and use values from around it. This helps keep data handy without passing it again and again.
Capturing values from context in Swift
let closure = { [captureList] in // code using captured values }
The captureList is optional and lets you control how values are captured.
By default, Swift captures values strongly, but you can use weak or unowned to avoid strong references.
x from the surrounding context and prints it.var x = 10 let closure = { print(x) } closure()
x is captured by value at the time of closure creation, so it prints 5 even if x changes later.var x = 5 let closure = { [x] in print(x) } x = 10 closure()
self weakly to avoid strong reference cycles.class Person { var name = "Alice" lazy var greet = { [weak self] in print("Hello, \(self?.name ?? \"Guest\")") } } let p = Person() p.greet()
This program creates a counter closure that captures count by reference. It increments and returns the count each time it is called.
func makeCounter() -> () -> Int { var count = 0 let counter = { count += 1 return count } return counter } let myCounter = makeCounter() print(myCounter()) print(myCounter())
Capturing by value means the closure keeps a copy of the value at the time it is created.
Capturing by reference means the closure uses the current value, which can change later.
Use capture lists to avoid memory problems like strong reference cycles.
Closures can capture values from their surrounding context.
By default, Swift captures variables by reference, but you can capture by value using capture lists.
Capture lists help manage memory and control how values are stored inside closures.