Why is the unowned reference type needed?
sobes.tech AI
Answer from AI
unowned references are used to resolve cyclic references (retain cycles) between objects, where both objects have strong references to each other, but one of the objects has a shorter or equal lifecycle.
unowned is used when it is known that the referenced object will not be nil during the entire lifetime of the object holding the reference. Unlike weak, accessing an unowned reference does not use Optional. If the object referenced by unowned is deallocated before the object with the unowned reference, a crash will occur.
Example of usage in closures:
class Person {
let name: String
var apartment: Apartment?
init(name: String) {
self.name = name
print("\(name) is being initialized")
}
deinit {
print("\(name) is being deinitialized")
}
}
class Apartment {
let unit: String
// Using unowned because it is known that
// Apartment cannot exist without Person
// (in this context). Person can be nil,
// but if Apartment exists, Person also exists.
unowned let tenant: Person?
init(unit: String, tenant: Person?) {
self.unit = unit
self.tenant = tenant
print("Apartment \(unit) is being initialized")
}
deinit {
print("Apartment \(unit) is being deinitialized")
}
}
var john: Person?
var unit4A: Apartment?
john = Person(name: "John Appleseed")
// In this example, tenant can be nil, so unowned optional
unit4A = Apartment(unit: "4A", tenant: john)
john!.apartment = unit4A
// Break strong references to test deallocation
john = nil
unit4A = nil
In this example, Person has a strong reference to Apartment (var apartment: Apartment?). Apartment could have a strong reference to Person, which would create a cycle. However, since in this context Apartment cannot exist without Person (who rents it), the reference from Apartment to Person is made unowned. Thus, when john = nil is set to nil, Person is deallocated, and subsequently (since there are no strong references to Apartment) Apartment is also deallocated.
Main differences from weak:
- Lifecycle:
unownedis used when the referenced object has the same or a longer lifecycle.weakis used when the referenced object can be deallocated earlier. - Optional:
unownedis not Optional (unless declared asunowned optional).weakis always Optional. - Safety: Accessing a property with an
unownedreference to an already deallocated object will cause a crash. Accessing aweakreference will returnnil.
Thus, unowned is a non-owning reference used when the existence of the referenced object is guaranteed as long as the object with the unowned reference exists.