Junior — Middle
Can you explain what it means to use a weak reference to self in closures?
sobes.tech AI
Answer from AI
Using a weak reference to self in closures in iOS (Swift) helps avoid retain cycles, which can lead to memory leaks. When a closure captures self as a strong reference, and self holds that closure, they keep each other alive, preventing memory from being released.
Example:
class MyClass {
var closure: (() -> Void)?
func setup() {
closure = { [weak self] in
guard let self = self else { return }
self.doSomething()
}
}
func doSomething() {
print("Action")
}
}
Here, [weak self] means that within the closure, self will be a weak reference, and if the object is destroyed, the reference will become nil, preventing a memory leak.