Junior — Middle
Can situations involving the use of weak (unowned) references lead to application failure? Provide an example.
sobes.tech AI
Answer from AI
Yes, using weak (unowned) references in Swift can lead to application crashes if the object referenced by the unowned reference has already been deallocated and an attempt to access this reference occurs later.
Unowned references assume that the object always exists as long as the reference exists. If this is not the case, the application will crash with an "EXC_BAD_ACCESS" error.
Example:
class Person {
var apartment: Apartment?
}
class Apartment {
unowned let tenant: Person
init(tenant: Person) {
self.tenant = tenant
}
}
var john: Person? = Person()
john!.apartment = Apartment(tenant: john!)
john = nil // the Person object is deallocated
// Now apartment.tenant is an unowned reference to an already deallocated object
// Accessing it will cause a crash
print(john!.apartment!.tenant) // crash
To avoid such crashes, you need to be sure that the unowned reference will not be used after the object is deallocated, or use weak references, which become nil after the object is deallocated.