Junior — Middle
Должен ли я добавлять weak self в список захвата для каждого замыкания в Swift?
sobes.tech AI
Answer from AI
It is not necessary to add weak self to the capture list for every closure in Swift. Using weak self is needed when the closure captures self and can lead to a retain cycle, for example, if the closure is stored in a property of an object or executed asynchronously and retains self longer than necessary.
If the closure is used locally and not stored, or does not cause retain cycles, then weak self can be omitted.
Example using weak self to prevent a retain cycle:
class ViewController: UIViewController {
var completionHandler: (() -> Void)?
func setup() {
completionHandler = { [weak self] in
guard let self = self else { return }
self.doSomething()
}
}
func doSomething() {
print("Action performed")
}
}
If self is not used in the closure or the closure is not stored, weak self is not needed.