Software Dev

Everything you need to know about [weak self]

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 yourself as [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 self for non-@escaping closures (ideally, omit it & trust the compiler)

Use weak self if you’re not sure

Upgrade self to a strongly-retained self at the top of your closure.

Via iOS Dev Weekly.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.