Junior — Middle
Under what circumstances should a weak reference be used inside a closure?
sobes.tech AI
Answer from AI
Weak references inside closures in iOS are used to prevent strong reference cycles (retain cycles), which can lead to memory leaks. This is usually relevant when a closure captures an object (for example, self) and is retained by that object, creating a mutual strong reference.
Use weak to reference self inside a closure if the closure is stored in a property of an object or may live longer than the function call, to avoid holding the object in memory after it should be released.
Example in Swift:
class ViewController {
var completion: (() -> Void)?
func setup() {
completion = { [weak self] in
guard let self = self else { return }
self.doSomething()
}
}
func doSomething() {
print("Action performed")
}
}
Here, [weak self] prevents a strong cycle between ViewController and the completion closure.