It has become pretty common among Swift experts to always use [weak self] inside of a closure to avoid retain cycles ...
Should one always use [weak self] to avoid retain cycles?
It has become pretty common among Swift experts to always use [weak self] inside of a closure to avoid retain cycles.
But is [weak self] needed or even recommended inside of all closures?
The answer is NO.
First of all [weak self] is only required for escaping closures that capture self. Escaping closures is just a fancy name for closures that get stored and do not get executed immediately, unlike the non-escaping ones.
Non-escaping closures do not pose a risk of introducing strong reference cycles, and therefore do not require the use of weak or unowned
While not using [weak self] in non-escaping closures does not cause reference cycles, it does cause delayed deallocation (which is not necessary a bad thing and can even be beneficial if one wants the code to finish executing before the object is killed). For example, a long operation inside of a closure can cause self to stay in memory until the operation is completed.
One last thing to note is that using [weak self] with guard let self = self (vs. self?) can also, for the same reasons as above, cause a delayed deallocation.
And truly the last thing, using [unowned self] is almost always a bad idea.
Want to learn more? This in-depth article on when you don’t always need weak self is a great read.
FAQ
- When do I actually need to use [weak self] in Swift closures?
- You only need [weak self] for escaping closures that capture self and could outlive the object, such as stored completion handlers or Combine subscriptions. Non-escaping closures cannot create retain cycles, so adding [weak self] there just delays deallocation without fixing a real problem.
- Why is [unowned self] almost always a bad idea in Swift closures?
- [unowned self] assumes the object will always be alive when the closure runs. If self is deallocated earlier, accessing it through an unowned reference will crash your app. In most cases it is safer to use [weak self] and handle the optional than to rely on unowned references.
Welcome to The infinite monkey theorem
Somewhere a monkey just typed Shakespeare in TypeScript. Be the first to read the masterpieces (and the hilarious misfires) landing on the blog.

