Junior — Middle
Can you list the main types of references used for working with objects in programming?
sobes.tech AI
Answer from AI
In programming, especially in iOS and Swift, the main reference types for working with objects include:
- Strong (strong reference) — holds the object in memory as long as the reference exists. The object will not be deallocated as long as there is at least one strong reference.
- Weak (weak reference) — does not hold the object in memory. If the object is deallocated, the weak reference automatically becomes nil. Used to prevent retain cycles.
- Unowned (unowned reference) — similar to weak, but not optional and does not become nil. Used when the reference is guaranteed to exist during use.
Example in Swift:
class Person {
var name: String
weak var apartment: Apartment? // weak reference
init(name: String) {
self.name = name
}
}
class Apartment {
let unit: String
unowned let tenant: Person // unowned reference
init(unit: String, tenant: Person) {
self.unit = unit
self.tenant = tenant
}
}