Sobes.tech
Junior — Middle

How does the use of unowned affect object lifetime management in programming?

sobes.tech AI

Answer from AI

In iOS (Swift), the keyword unowned is used to declare a weak reference to an object that does not increase the reference count but assumes that the object will exist for the lifetime of the reference.

Using unowned helps avoid retain cycles, which can lead to memory leaks. Unlike weak, an unowned reference is not optional and does not become nil after the object is deallocated, so it is safe to use only if it is guaranteed that the object will exist longer than the reference.

Example:

class Person {
    var name: String
    init(name: String) { self.name = name }
    var apartment: Apartment?
}

class Apartment {
    let unit: String
    unowned let tenant: Person
    init(unit: String, tenant: Person) {
        self.unit = unit
        self.tenant = tenant
    }
}

let john = Person(name: "John")
let apt = Apartment(unit: "4A", tenant: john)
john.apartment = apt

Here, Apartment holds an unowned reference to Person to avoid a cycle, assuming that Person will always exist as long as Apartment exists. If Person is deallocated earlier, accessing the unowned reference will lead to a runtime error.