Middle
What do you know about capture list in Swift?
sobes.tech AI
Answer from AI
In Swift, capture list is used in closures to manage the capture of variables from the surrounding context, especially to avoid strong reference cycles (retain cycles).
The capture list is written in square brackets before the closure body and allows specifying how variables are captured — by strong reference, weak, or unowned.
Example:
class ViewController {
var name = "Swift"
lazy var closure: () -> Void = { [weak self] in
guard let self = self else { return }
print(self.name)
}
}
Here, [weak self] prevents a strong reference to self inside the closure, helping to avoid memory leaks.
Thus, capture list is a tool for controlling the lifecycle of objects captured by the closure.