Middle
What are the advantages of using 'Unowned' in Swift?
sobes.tech AI
Answer from AI
- Preventing strong reference cycles (retain cycles).
- Used when one object has the same or longer lifetime than another and will always have a reference to that other object.
- The compiler guarantees that an 'unowned' reference always points to a valid object. If you try to access an 'unowned' reference after the object has been deallocated, the application will crash. This makes errors with 'unowned' more explicit and helps detect issues faster.
- Does not increase the reference count of the object, making it slightly more efficient than 'weak'.
class Person {
let name: String
var car: Car?
init(name: String) {
self.name = name
print("\(name) is being initialized")
}
deinit {
print("\(name) is being deinitialized")
}
}
class Car {
let model: String
unowned let owner: Person // Unowned reference to Person
init(model: String, owner: Person) {
self.model = model
self.owner = owner // owner must not be nil
print("\(model) is being initialized")
}
deinit {
print("\(model) is being deinitialized")
}
}
var kevin: Person? = Person(name: "Kevin")
var bmw: Car? = Car(model: "BMW", owner: kevin!) // Pass kevin as non-optional
kevin?.car = bmw
// Setting kevin to nil will deinitialize both objects,
// since owner is unowned and does not create a strong reference cycle.
kevin = nil
// Output:
// Kevin is being initialized
// BMW is being initialized
// Kevin is being deinitialized
// BMW is being deinitialized