swift

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 ...

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? Here is a great article.

Should one always use weak self to avoid retain cycles?

Subscribe to The infinite monkey theorem

Get the latest posts delivered right to your inbox