Explain the difference between 'weak' and 'unowned' references in Swift.

Instruction: Describe the concepts of 'weak' and 'unowned' references and when it's appropriate to use each.

Context: This question tests the candidate's knowledge of memory management in Swift, specifically understanding the difference between 'weak' and 'unowned' references and their use cases to prevent retain cycles.

Updated

Official answer

Both weak and unowned references avoid retaining a class instance. A weak reference must be an optional variable and becomes nil when its target is deallocated. Use it when the target may go away independently, then handle the missing value.

A safe unowned reference assumes its target remains alive whenever that reference is accessed. It does not automatically become nil after deallocation; accessing a dangling safe unowned reference traps. Swift permits both nonoptional and optional unowned references. An unowned optional may be nil, but a nonnil value must still refer to a live object; it is not a zeroing weak reference. Avoid unowned(unsafe) unless its unchecked lifetime risks are specifically justified.

This complete example uses weak for a watcher that can outlive its owner and unowned for a dependent used only while its owner is alive:

final class Owner { let name = "owner" }
final class Watcher { weak var owner: Owner? }
final class Dependent {
    unowned let owner: Owner
    init(owner: Owner) { self.owner = owner }
    func label() -> String { owner.name }
}
let watcher = Watcher()
do {
    let owner = Owner()
    watcher.owner = owner
    let dependent = Dependent(owner: owner)
    assert(dependent.label() == "owner")
    withExtendedLifetime(owner) {
        assert(watcher.owner != nil)
    }
}
assert(watcher.owner == nil)

The example's lifetime arrangement is deliberate. A class name such as Child, or creating a closure in viewDidLoad, does not prove that arrangement holds after navigation or asynchronous work. Trace the ownership graph and choose weak when the target can disappear. Do not replace every strong capture mechanically: strong ownership is often appropriate, and a cycle requires a path back to the owner.

ARC and closure cycles

Related Questions