I have been doing some research on the unowned reference type, trying to wrap my head around how it compares to a strong reference.
After talking it through with my colleague, looking through articles, I finally came across the Swift doc that explains how unowned is different from weak in that "If the captured reference will never become nil, it should always be captured as an unowned reference, rather than a weak reference." - https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html
If I understand
unowned correctly, it seems to me that it is just like a 'strong' reference that doesn't increase the reference count. Is that accurate?
Thank you for your help!
If I understand unowned correctly, it seems to me that it is just like a 'strong' reference that doesn't increase the reference count. Is that accurate?
Yes, it's accurate as far as it goes. But it isn't really about the reference count, except secondarily. It's about
release. A strong reference calls
retain on assignment, and deals with
release later. An unowned reference doesn't; it does nothing at all to manage the assigned object's memory.
Hence, you need the unowned object to have a guaranteed lifecycle longer than this object, because the unowned object can in theory go out of existence while this object still exists, and if it does that, the reference to the unowned object will be a reference to garbage (a dangling pointer) and a mysterious crash may be in your future.