What is unowned(unsafe), and when would you ever use it?

3.2.4 · L5 · Learning

Predict first

Which of these is checked at runtime when the target is gone?

// A: unowned
// B: unowned(unsafe)
// C: both
  • A
  • B
  • C

Mental model. Unowned is a signpost that tells you if the building is gone. Unsafe is a signpost painted on the ground that keeps pointing at the empty plot.

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 retain, and it does not even update the unowned counter, so it is the cheapest reference there is. If the target dies, the reference dangles, and reading it is undefined behaviour: a crash, silent corruption, or apparently working code that breaks later.

It exists for performance-critical code where another mechanism proves the lifetime and the runtime check is measurable overhead. In everyday app code do not use it: unowned costs almost the same and fails loudly. When you need explicit control, prefer Unmanaged<T>, which makes the ownership transfer visible in the code.

unowned checks the object’s state and traps. unowned(unsafe) skips the check and reads whatever memory is there.

Common traps

  • Using it to silence a retain cycle warning. You trade a leak for a possible use-after-free.
  • Assuming it behaves like unowned in Debug. It does not check in any build.

They might follow up with

  • Where does the standard library use it? In internals where the owner is guaranteed by construction, such as certain iterator and buffer types.
  • How is it different from Unmanaged? Unmanaged is an explicit wrapper with retain and release calls you control.

Related questions

  • 3.2.1 What is the difference between strong, weak, unowned and unowned(unsafe)?
  • 3.6.3 What is Unmanaged, and what do takeRetainedValue and takeUnretainedValue mean?
  • 3.2.5 What happens to an object’s memory while unowned references to it still exist?

← How do you decide between weak, unowned and strong for a…   What happens to an object’s memory while unowned references to it… →