Junior — Middle
Can you explain the concept of Capture List in the context of the Swift language and its application?
sobes.tech AI
Answer from AI
In Swift, Capture List is a mechanism that allows controlling how a closure captures variables from its surrounding context, especially for memory management and preventing retain cycles.
The Capture List is written in square brackets before the closure body and specifies how to capture variables: by strong reference, weak, or unowned.
Example:
class ViewController {
var name = "Main"
func setup() {
let closure = { [weak self] in
guard let self = self else { return }
print(self.name)
}
closure()
}
}
Here, [weak self] prevents a strong retain cycle between the closure and the self object, which is important for proper memory deallocation.
Thus, Capture List helps manage the lifecycle of objects within closures and avoid memory leaks.