unowned var view = UIView() then print(view) — what happens?

1.5.6 · L2 · Interview

Predict first

What happens?

final class View {}

unowned var view = View()
print(view)
  • Prints the view
  • Prints nil
  • Crashes

Mental model. You kept a note saying “my friend lives at 42 Main St” but never made sure anyone actually moved in. The address is real; the person is not.

The UIView() has no strong owner. unowned does not retain, so the instance is deallocated immediately. Reading view afterwards is undefined behaviour — in practice a crash, or garbage memory that happens to look valid.

weak would instead have become nil, which is why weak is the safe default. A strong local reference would have kept the view alive.

Nothing owns the new instance, so it is freed immediately. Reading an unowned reference to a freed object traps. The compiler even warns about it.

Common traps

  • “unowned keeps it alive like a strong reference.” It does not retain at all.
  • “weak would also crash.” No — weak zeroes out, so you get a clean nil.
  • Thinking compile-time checks catch this. This compiles; the failure is at runtime.

They might follow up with

  • When is unowned actually correct? When the referenced object provably outlives the holder — e.g. a child object pointing back at a parent that owns it.
  • What is unowned(unsafe)? No runtime check at all; it does not nil out and does not trap reliably. Reserved for very specific performance cases.

Related questions

  • 1.5.4 What does a capture list like [weak self], [unowned self], [self], or [foo] actually do?
  • 1.10.7 How do you set a language bar for a large iOS org (Swift 6, existentials, macros, concurrency)?
  • 1.1.6 When is teaching “always use structs” harmful on a team?

← Why does this print the new city without a capture list, and the old…   What is @autoclosure? When is it justified? →