If none of the above makes sense:
tl;dr
Just like an implicitly unwrapped optional
, If you can guarantee
that the reference will not be nil at its point of use, use unowned.
If not, then you should be using weak.
Explanation:
I retrieved the following below at: weak unowned link. From what I gathered, unowned self can't be nil but weak self can be, and unowned self can lead to dangling pointers...something infamous in Objective-C. Hope it helps
"UNOWNED Weak and unowned references behave similarly but are NOT the same."
Unowned references, like weak references, do not increase the retain count of the object being referred. However, in Swift, an unowned reference has the added benefit of not being an Optional. This makes them easier to manage rather than resorting to using optional binding. This is not unlike Implicitly Unwrapped Optionals . In addition, unowned references are non-zeroing. This means that when the object is deallocated, it does not zero out the pointer. This means that use of unowned references can, in some cases, lead to dangling pointers. For you nerds out there that remember the Objective-C days like I do, unowned references map to unsafe_unretained references.
This is where it gets a little confusing.
Weak and unowned references both do not increase retain counts.
They can both be used to break retain cycles. So when do we use them?!
According to Apple's docs:
“Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialisation.”
onChange
should be a[weak self]
closure, since it's a public (internally, but still) property, so another object could get and store the closure, keeping the TempNotifier object around (indefinitely if the using object didn't let go of theonChange
closure until it sees theTempNotifier
is gone, via its own weak ref to theTempNotifier
). Ifvar onChange …
wereprivate var onChange …
then[unowned self]
would be correct. I'm not 100% certain of this though; somebody correct me please if I'm wrong. – Slipp D. Thompson[]
? I can't find the explanation in the Apple docs. – bibscy{}
is the empty closure (the instance of the closure) as the default (doesn't do anything),(Int) -> Void
is the closure definition. – Jake Lin