Junior — Middle
What types of unowned references exist in programming languages, for example, Swift?
sobes.tech AI
Answer from AI
In Swift, there are several types of unowned references used to prevent strong reference cycles without increasing the object's reference count:
-
unowned — an unsafe, non-owning reference, assumed to exist longer than the reference. If the object is deallocated, accessing an unowned reference will cause a runtime error.
-
weak — a weak reference that automatically becomes nil when the object is deallocated. Used when the reference may become nil.
Example:
class Person {
var apartment: Apartment?
}
class Apartment {
unowned let tenant: Person
init(tenant: Person) {
self.tenant = tenant
}
}
let john = Person()
let apt = Apartment(tenant: john)
john.apartment = apt
Here, Apartment holds an unowned reference to Person, assuming that Person will exist longer. If Person is deallocated earlier, accessing tenant will cause an error.