Junior — Middle
Explain what a capture list is in programming languages.
sobes.tech AI
Answer from AI
The capture list in Swift is used in closures to specify how variables from the external context are captured and used inside the closure.
By default, closures capture variables by reference, which can lead to retain cycles, especially when working with classes. The capture list allows you to explicitly specify how to capture variables — for example, by value (weak, unowned) or by copying.
Example:
class ViewController {
var name = "Main"
func setup() {
let closure = { [weak self] in
print(self?.name ?? "No name")
}
closure()
}
}
Here, [weak self] prevents a strong retain cycle between the closure and the class object.