Can you explain the concept of unowned in the context of safe reference handling in Swift?
sobes.tech AI
Answer from AI
In Swift, unowned is a reference modifier that indicates the reference does not own the object it refers to, but it is assumed that the object will exist at the time of access.
Unlike weak, unowned is not an optional reference and does not hold nil. If the object referenced by unowned has already been deallocated, accessing such a reference will cause a crash.
unowned is used to prevent strong reference cycles (retain cycles), when one of the references is guaranteed to exist longer than the other.
Example:
class Person {
let name: String
var apartment: Apartment?
init(name: String) { self.name = name }
}
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, because Person is guaranteed to exist longer than Apartment. This prevents a retain cycle but requires confidence that tenant will not be deallocated before Apartment.