DEV Community

When to use weak self and why

Donny Wals on November 08, 2019

We all want to write good, beautiful and stable code. This includes preventing memory leaks, which we can, using [weak self] when writing a closure...
Collapse
 
gualtierofr profile image
Gualtiero Frigerio

I think this is a good explanation of weak self

I'd only mention this evolution introduced in 4.2
github.com/apple/swift-evolution/b...
so you can use
guard let self = self else { return }
instead of having strongSelf or another variable name in the closure.

Collapse
 
donnywals profile image
Donny Wals

Sounds like a good addition, I didn't add it to avoid confusion (self = self might look weird to folks who are learning about this stuff for the first time). Adding a separate callout might be nice though. Thanks!

Collapse
 
gualtierofr profile image
Gualtiero Frigerio

I guess for the purpose of an article strongSelf can be better as self = self may be confusing to some people as you say.
I've used strongSelf and weakSelf many times in Objective-C and I'm glad it is now possible to just use self in Swift now

Collapse
 
kodelit profile image
kodelit • Edited

Nice reading. You read about things you think you know, and yet there is always something you didn't know. :)

One thing I would like to know after reading this post is the explanation why when you use unowned reference it sometimes crashes and that It's because the other difference between weak and unowned:

  • weak will not retain the reference counter of the object and the variable will be set to nil when the last strong reference to the object was removed.
  • unowned will also not retain reference counter of the object, but variable will still hold reference to an object even if it does not exist anymore, and if you do not set it to nil explicitly (like in old times of Manual Memory Management in Objective-C) it will cause crash if you try to use it.
Collapse
 
kesprit profile image
kesprit

Very good post, thank you! šŸ‘

I didn't know about capture lists and now it's so obvious!
Many times I could just capture a property rather than self.