Weak Self: Closure Rules of Thumb
In Swift, you can weak-ify references to
self
in escaping closures, and then you need to deal with the case that the reference is gone when the block is called.Last month, Benoit Pasquier and Chris Downie presented different takes on the problem. That discussion was excellent. It prompted me to take some more time to revisit this problem systematically, and I took away a couple of notes for future-me.
The three popular options as Chris listed them are these:
- Do not capture strong reference
- Override
self
with strong reference- Bind
strongSelf
As always, either way has its pitfalls.
[…]
[When overriding
self
, you] can forgetweak
ifying inner closures and accidentally create a retain cycle again!
I think we still see this discussed because nobody has a great solution. There are some common patterns, but they are verbose and still easy to get wrong.
I tend to upgrade self
at the top of the closure. For common cases like notifications and timers, I have the caller handle this and pass the strong reference into the closure if it’s not nil
.
Previously:
- Swift “guard” Capture Specifier Pitch
- Implicit Capturing of Self in Swift 5.3
- Dealing With Weak in Closure-based Delegation
- Stop the weak-strong Swift Dance
- @weakify and @strongify Macros
1 Comment RSS · Twitter
... [When overriding self, you] can forget weakifying inner closures and accidentally create a retain cycle again! ...
So true. I still get confused sometimes.