weak vs unowned

Memory & ARC Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

A CreditCard always belongs to a Customer and is destroyed with it. The card holds a reference back to its customer. Which declaration?

Options
Hint 1 of 1

Can the card outlive the customer?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A unowned let customer: Customer

Correct. The customer always outlives the card, and the property can be non-optional.

Why not the others?
  • B weak var customer: Customer?. It is safe, but adds an optional for a reference that can never be nil while the card exists.
  • C let customer: Customer (strong). Customer → card → customer is a retain cycle.
  • D unowned(unsafe) let customer: Customer. It drops the safety check for no benefit.

30-second answer

Both avoid increasing the strong count. weak is optional and becomes nil when the object is freed, so it is always safe; use it when the other object can disappear first, like delegates. unowned is non-optional and assumes the object outlives the reference; accessing it after deallocation crashes. Use unowned only when lifetimes are guaranteed.

Practise saying it · 30 s. No recording, just a timer

Explain weak vs unowned.

Say your answer out loud, then check which of these points you covered:

  • weak is optional and zeroing
  • unowned assumes the lifetime
  • Default to weak

Deep dive

weak must be var and optional.

unowned access is checked: a freed object traps instead of corrupting memory.

unowned(unsafe) removes the check, so use-after-free is undefined behaviour.

When unsure, use weak.

Common mistakes

  • Using unowned in callbacks that may run after the screen closes.
  • Using strong references for back-pointers.

Senior take & follow-ups

Seniors decide by lifetime guarantees, and default to weak.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why does weak require var and optional?

    Show hint

    ARC sets it to nil when the object is freed.

  2. Example where unowned is right?

    Show hint

    A card that can't exist without its customer.

Suggest a fix if something here is wrong or out of date.