In Swift, when do you declare a back-reference `unowned` instead of `weak`, and what happens if it is read after its object is gone?
answer
- who outlives whom
- non-optional, never zeroed
- a checked trap, not nil
- unowned(unsafe) drops the check
basics
~20 sUse unowned when the referenced object always lives at least as long as the holder, so it never needs to be nil. Reading an unowned reference after its object is destroyed traps; unowned(unsafe) drops that check and reads freed memory.
solid answer
~50 sBoth `weak` and `unowned` break a strong reference cycle because neither keeps its object alive; they differ in what they promise. A `weak` reference is optional and ARC sets it to `nil` when the object is deallocated, so it fits an object that may go away first, like a delegate. An `unowned` reference is normally non-optional and ARC never sets it to `nil`: you are asserting the other object has the same or a longer lifetime, such as a credit card that is created for one customer, held only by that customer and pointing back at it. If the assertion is wrong, reading the reference stops the program with "Attempted to read an unowned reference but object … was already destroyed", in debug and optimized builds alike. `unowned(unsafe)` removes even that check, so a stale read touches memory where the object used to be.
code
swift · 23 linesfinal class Customer {
let name: String
var card: CreditCard?
init(name: String) { self.name = name }
deinit { print("Customer deinit") }
}
final class CreditCard {
let number: UInt64
unowned let customer: Customer // no retain, never becomes nil
init(number: UInt64, customer: Customer) {
self.number = number
self.customer = customer
}
func printHolder() { print(customer.name) }
}
var john: Customer? = Customer(name: "John Appleseed")
john!.card = CreditCard(number: 1234_5678_9012_3456, customer: john!)
let pending = john!.card! // e.g. a payment request still holds the card
pending.printHolder() // prints "John Appleseed"
john = nil // the customer deinitializes
pending.printHolder() // traps: the unowned referent was already destroyedgo deeper
Remember that weak becomes nil and is optional, while unowned is non-optional and never becomes nil. Both stop a reference from keeping its object alive.
Explain the lifetime rule from the Swift book and what the run-time check does: a read of a destroyed unowned referent traps instead of returning nil.
Show where unowned breaks in production: an owned object that escapes into a long request or callback and outlives its owner, and why unowned(unsafe) turns that crash into memory corruption.
Weigh a diagnosable trap against a silent nil path: when an unowned reference documents a real lifetime guarantee, and when the team should simply default to weak.
## Two non-owning references In Swift, a stored property or variable that holds a class instance is a **strong reference** unless you say otherwise. To break a strong reference cycle, one edge must be **non-owning**, and Swift offers two kinds: - **`weak`** — does not keep the object alive; ARC sets it to `nil` when the object is deallocated, so it must be an optional type. - **`unowned`** — does not keep the object alive either, but ARC never sets it to `nil`. It is normally non-optional, and you read it like an ordinary property. Both make the cycle go away. The choice is about **lifetime**, not about which one is faster or shorter to type. ## The lifetime rule The Swift book states it directly: use a weak reference when the other instance has a **shorter** lifetime and can be deallocated first; use an unowned reference when the other instance has the **same or a longer** lifetime. | Modifier | Optional? | After the object is gone | Fits | |---|---|---|---| | `weak` | always | reads `nil` | delegates, observers, anything that may close first | | `unowned` | usually not (optional allowed since Swift 5.0) | a read traps | a child whose owner always outlives it | | `unowned(unsafe)` | usually not | a read accesses freed memory | proven lifetimes where the check itself is the cost | The Swift book's own `unowned` example is a `Customer` and its `CreditCard`: a card is always created for one customer and held only by that customer, so the customer lives at least as long as the card. `unowned let customer: Customer` lets the card read its holder without unwrapping an optional. A view model pointing back at its screen is usually **not** this case, even when the screen creates it: in-flight tasks and closures routinely keep a view model alive after its screen closes, so that back-reference takes `weak`. ## What happens when the assumption breaks The promise behind `unowned` is checked at run time. If something else keeps the card alive after the customer is gone, for example a payment request that captured the card, then the next read of `customer` stops the program: ```plaintext Fatal error: Attempted to read an unowned reference but object 0x10334d1b0 was already destroyed ``` Key points about that trap: 1. It happens in **optimized builds too**. Plain `unowned`, spelled `unowned(safe)` in full, keeps its check under `-O`. 2. It is **diagnosable**: the crash points at the read that broke the lifetime assumption, which is easier to track down than a silent `nil`. 3. It is still a crash in front of the user, so `unowned` is only right when the lifetime is guaranteed by the design, not merely likely. ## Unowned optionals and unowned(unsafe) Since Swift 5.0, `unowned` can be applied to an optional class type, as in `unowned var nextCourse: Course?`. You may assign `nil` yourself, but ARC still never sets it to `nil` for you, so you remain responsible for clearing it before its object goes away. That is the whole difference from `weak`. `unowned(unsafe)` keeps the same non-owning shape but **disables the run-time safety check**. The Swift book's example reason is performance. A read after deallocation then touches the memory where the object used to be: it may appear to work, return garbage or crash later somewhere unrelated. It is the Swift spelling of an unretained pointer and belongs only where a profile shows the check matters and the lifetime is proven by construction. ## Why not always weak Defaulting to `weak` everywhere is safe, but it is not free. Every read becomes an optional that has to be unwrapped, and a `nil` read usually means the code silently skips its work. When the design says the owner must outlive the holder, that silent skip hides a bug: the card kept being charged after its customer was gone and nobody noticed. An `unowned` reference documents the lifetime in the declaration and turns a broken assumption into a crash report that points at the exact read. ## Choosing in practice - Ask "can the other object be freed while this one is still in use?" If yes, or if you are not sure, use `weak`. - Use `unowned` for a reference from an owned child back to its owner, set once in the initializer and never handed to longer-lived code. - Be suspicious of `unowned` on anything that escapes: a card handed to a long payment request can outlive the customer even though the customer created it. - Prefer a trap you can diagnose over `unowned(unsafe)`; never use the unsafe form to silence a crash. - The same `weak` and `unowned` choice appears in closure capture lists, which the Swift material on capture lists covers; the lifetime rule is identical.
- Does an unowned reference still trap in an optimized release build?Yes. Plain `unowned`, which can also be written `unowned(safe)`, keeps its run-time check under `-O`, so a read after the object is destroyed stops with "Attempted to read an unowned reference but object … was already destroyed". Only `unowned(unsafe)` removes the check, and then a stale read accesses freed memory instead of failing cleanly.
- Can an unowned reference be optional, and how is that different from weak?Yes, since Swift 5.0: `unowned var nextCourse: Course?`. You may store `nil` in it yourself, but ARC never sets it to `nil` when the object is deallocated. You stay responsible for clearing it before the object goes away; a `weak` reference is cleared for you.
- Why would anyone write `unowned(unsafe)`?To remove the run-time safety check on a reference whose lifetime is proven by construction, on a path where profiling shows the check matters; the Swift book gives performance as the example reason. The price is that a mistake no longer traps: a read after deallocation touches memory where the object used to be, which is undefined behaviour and much harder to diagnose.
- unowned is a faster weak that also becomes nil automatically.
- A dangling unowned reference silently returns stale data in release builds.
- unowned can never be applied to an optional type.
- Use unowned whenever the other object will probably still be alive.
- unowned(unsafe) is just another spelling of plain unowned.