Junior — Middle
Why is it recommended to use a weak reference to the object itself (weak self) in code that uses closures?
sobes.tech AI
Answer from AI
Using a weak reference (weak self) in closures is necessary to prevent strong reference cycles (retain cycles), which lead to memory leaks.
When a closure captures self as a strong reference, and self contains that closure (for example, in a property), they hold onto each other, and neither object is released.
An example of using a weak reference:
someAsyncCall { [weak self] in
guard let self = self else { return }
self.doSomething()
}
Here, self is captured weakly, so if the self object is destroyed before the closure executes, the closure will not hold it in memory, preventing a leak.