memory-managementswiftautomatic-ref-counting

What is the difference in Swift between 'unowned(safe)' and 'unowned(unsafe)'?


Apple's Swift Programming Language Guide mentions the capture specifiers unowned(safe) and unowned(unsafe), in addition to weak and unowned.

I (think I) understand the differences between weak and unowned; but what is the difference between unowned(safe) and unowned(unsafe)? The guide doesn't say.


Please: Don't rely on simply stating an Objective-C equivalent.


Solution

  • From what I understand, although I can't find a definitive source from Apple, unowned can be broken into two flavors, safe and unsafe.

    A bare unowned is unowned(safe): it is a specially wrapped reference which will throw an exception when a dealloced instance is referenced.

    The special case is unowned(unsafe): it is the Swift equivalent of Objective C's @property (assign) or __unsafe_unretained. It should not be used in a Swift program, because its purpose is to bridge to code written in Objective C.

    So, you will see unowned(unsafe) when looking at the import wrapper for Cocoa classes, but don't use it unless you have to, and you will know when you have to.


    Update

    __unsafe_unretained is a simple pointer. It will not know when the instance being pointed at has be dealloced, so when it's dereferenced, the underlying memory could be garbage.

    If you have a defect where a dealloced __unsafe_unretained variable is being used, you will see erratic behavior. Sometimes enough of that memory location is good enough so the code will run, sometimes it will have been partially overwritten so you will get very odd crashes, and sometimes that memory location will contain a new object so you will get unrecognized selector exceptions.

    Transitioning to ARC Release Notes

    __unsafe_unretained specifies a reference that does not keep the referenced object alive and is not set to nil when there are no strong references to the object. If the object it references is deallocated, the pointer is left dangling.