This is a post about the idea of “weak self” in the Swift programming language. It is not a post about self-doubt. You are strong. You are capable. You matter. 😉
But your Swift object might be weak, or at least @escaping and weakly held. 🤷🏻♂️ If this makes no sense, maybe it’s time to check out some pictures or quotes.
If you’re a Swift programmer, you probably know that if you need a reference to back to the calling
self in a closure, and that closure might last longer than
self, then you should send that closure your
[weak self] so you don’t end up with a retain cycle and a memory leak.
Still, it can get a bit confusing. What do you do if the weak
self is actually gone when you execute the closure? Can the weak
self disappear in the middle of the closure?
Fortunately, the Swift blogger Christian Tietze has all the answers. Or at least he has found some answers and summarized them nicely.
In the end, it all points to Chris Downie’s rules of thumb.
Only use a strong
@escapingclosures (ideally, omit it & trust the compiler)
weak self if you’re not sure
selfto a strongly-retained
selfat the top of your closure.
Via iOS Dev Weekly.