Junior — Middle
What is the difference between Weak and Unowned references in memory management?
sobes.tech AI
Answer from AI
In Swift, weak and unowned references are used to prevent strong reference cycles (retain cycles) when managing memory, but they differ in behavior and usage.
-
Weak:
- Can be
nil. - Declared as an optional type (
var delegate: SomeDelegate? weak). - Used when the reference can become
nilduring the lifetime of the object, for example, delegates. - The system automatically sets a
weakreference tonilwhen the object it references is deallocated.
- Can be
-
Unowned:
- Cannot be
nil(non-optional type). - Used when the reference is guaranteed to exist during the lifetime of the object, for example, parent-child relationships.
- If the object referenced by
unownedis already deallocated, accessing it will lead to a runtime error (crash).
- Cannot be
Example:
class Person {
var apartment: Apartment?
}
class Apartment {
unowned let tenant: Person
init(tenant: Person) {
self.tenant = tenant
}
}
// Here, tenant is unowned because the apartment cannot exist without a tenant.
class DelegateHolder {
weak var delegate: SomeDelegate?
}
// Delegate is weak because it can be deallocated earlier.
Thus, weak is suitable for references that can become nil, and unowned for references that should always be valid during the object's lifetime.