39

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.

5 Answers 5

45

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.

3
  • 1
    But what do those Objective-C equivalents mean?
    – orome
    Commented Oct 24, 2014 at 22:22
  • 22
    So, to summarize, unlike strong references, weak and all the unowneds do not contribute to reference counting. So once all strong references are gone, the instance referenced will be deallocated (when only weak and unowned references to it remain); weak references will be set to nil (they thus have optional type), while unowned will not be. However unowned(safe) references to deallocated instances will throw a predictable exception when accessed, while unowned(unsafe) references will act like a simple old pointer and behave unpredictably. Right?
    – orome
    Commented Oct 25, 2014 at 13:12
  • 5
    @raxacoricofallapatorius, no that’s not right. unowned and unowned(safe) do incur reference counting cost—that is the cost of safety, and why even make unowned(unsafe) available otherwise?—and it’s currently worse than regular strong reference counting cost because ARC isn’t optimizing for it. Neither throws an exception; they trap when misused, permanently stopping the program. Commented Feb 21, 2016 at 10:59
28

Here is a quote from Apple Developer Forums:

unowned vs unowned(safe) vs unowned(unsafe)

unowned(safe) is a non-owning reference that asserts on access that the object is still alive. It's sort of like a weak optional reference that's implicitly unwrapped with x! every time it's accessed. unowned(unsafe) is like __unsafe_unretained in ARC—it's a non-owning reference, but there's no runtime check that the object is still alive on access, so dangling references will reach into garbage memory. unowned is always a synonym for unowned(safe) currently, but the intent is that it will be optimized to unowned(unsafe) in -Ofast builds when runtime checks are disabled.

1
  • I just debugged a crash using unowned with runtime checks disabled, compiled optimized, where __deallocating_deinit asserted in the presence of an unowned reference to a deleted object. (Though my code never referenced it after the object went away.) So there is still a difference between unowned(unsafe) and unowned compiled with safety checks disabled. Detailed thread on this: twitter.com/RonAvitzur/status/1463576340519473159
    – Avitzur
    Commented Nov 24, 2021 at 18:39
13

Variable is accessed when it was dellocated already with attribute:

unowned

  • Program knows it is invalid, and goes crash immediately.
  • Behavior is defined.

unowned(unsafe)

  • Program knows nothing.
  • It may crash immediately.
  • It may access unknown memory address and have strange state until it dies at surprise location.
  • Behavior is undefined. Life gets harder.
5

A simple Definition. which would clear the confusion.

-- unowned attributes : If you try to access an unowned reference after the instance that it refers to is deallocated, your program will crash.

-- unowned(Unsafe) attributes: If you try to access an unsafe unowned reference after the instance that it refers to is deallocated, your program will try to access the memory location where the instance used to be, which is an unsafe operation. (no guarantee wether this would executes or crashes)

0

In simple words

unowned(safe) or simply unowned - Crash the application if we try to refer the deallocated object.

unowned(unsafe) - Don't crash the application but instead try to find the memory location where the referred object was stored before de-initialisation.

Consider example -

class Customer {
    let name: String
    var card: CreditCard?
    init(name: String) {
        self.name = name
    }
    deinit {
        print("\(name) is being deinitialized")
        print("It's Credit card is - ", card)
    }
}


class CreditCard {
    let number: UInt64
    unowned(unsafe) let customer: Customer
    init(number: UInt64, customer: Customer) {
        self.number = number
        self.customer = customer
    }
    deinit {
        print("Card #\(number) is being deinitialized")
        print("It's customer is - ", customer.name)
    }
}

var customer: Customer? = Customer(name: "Stackoverflow")
customer!.card = CreditCard(number: 1234_5678_9012_3456, customer: customer!)
customer = nil

When you run this code in playground then your will get the following output -

Stackoverflow is being deinitialized
It's Credit card -  Optional(__lldb_expr_16.CreditCard)
Card #1234567890123456 is being deinitialized
It's customer -  Stackoverflow

The main thing to check here is even the Stackoverflow was deinitialised but still we can print that in CreditCard's deinit call

If you will try to call the same code with unowned instead of unowned(unsafe) then it will crash with following logs

Stackoverflow is being deinitialized
It's Credit card -  Optional(__lldb_expr_20.CreditCard)
Card #1234567890123456 is being deinitialized
Fatal error: Attempted to read an unowned reference but object 0x600000291830 was already deallocated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.