Sobes.tech
Junior — Middle

In which cases is it preferable to use unowned instead of weak in memory management?

sobes.tech AI

Answer from AI

In Swift, weak and unowned are used to prevent strong reference cycles but are applied in different situations:

  • weak is an optional reference that automatically becomes nil when the object it references is deallocated. It is used when the reference can become nil during the object's lifetime.

  • unowned is a non-optional reference that assumes the object it references will always exist during its use. If the object is deallocated, accessing unowned will cause a runtime error.

It is preferable to use unowned when:

  • The reference should always point to an existing object (for example, a parent object that lives longer than the child).
  • You are sure that the lifetime of the object you reference is not shorter than the lifetime of the reference.

Example:

class Customer {
    let name: String
    var card: CreditCard?
    init(name: String) {
        self.name = name
    }
}

class CreditCard {
    let number: UInt64
    unowned let customer: Customer
    init(number: UInt64, customer: Customer) {
        self.number = number
        self.customer = customer
    }
}

let john = Customer(name: "John Appleseed")
john.card = CreditCard(number: 1234_5678_9012_3456, customer: john)

Here, CreditCard has an unowned reference to Customer because the card cannot exist without the customer, and the customer lives longer than the card.

In which cases is it preferable to use unowned… - sobes.tech