Sobes.tech

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 nil during the lifetime of the object, for example, delegates.
    • The system automatically sets a weak reference to nil when the object it references is deallocated.
  • 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 unowned is already deallocated, accessing it will lead to a runtime error (crash).

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.

What is the difference between Weak and Unowned… - sobes.tech