3.2 · strong, weak, unowned, unowned(unsafe)

Four ways to point at an object. They differ in one question: what happens when the object is already gone?

Mental model. Choose by lifetime. If you can promise the target outlives you, use unowned. If you cannot, use weak, where “gone” is just nil instead of a crash.

The reference kinds

What each one promises and costs.

  1. What is the difference between strong, weak, unowned and unowned(unsafe)? 3.2.1 · L1
    A strong reference keeps its target alive: it holds one count. The other three do not, and they differ in what you see after the target dies. A weak reference…
  2. Why is a weak reference optional, what can be weak, and what is the trap when reading one? 3.2.2 · L2
    The runtime zeroes a weak reference when its target dies, which is why the type must be optional: nil is the only value that means “gone”. Only class types…

Choosing and what lies beneath

The decision rule, the unsafe variant, and what the runtime does with unowned.

  1. How do you decide between weak, unowned and strong for a back-reference? 3.2.3 · L2
    Draw the ownership tree: every object has one clear owner that holds it strongly. A reference against that direction (child to parent, delegate to owner…
  2. What is unowned(unsafe), and when would you ever use it? 3.2.4 · L5
    unowned(unsafe) is a reference with no ownership and no safety check: the Swift equivalent of a C pointer, or Objective-C’s __unsafe_unretained. It does not…
  3. What happens to an object’s memory while unowned references to it still exist? 3.2.5 · L5
    Every Swift object has a strong count and a separate unowned count. When the strong count reaches zero, deinit runs and the stored properties are destroyed…

More in Memory, ARC & runtime