Sobes.tech
Junior

What is the weak memory modifier in Swift?

sobes.tech AI

Answer from AI

The weak modifier is used to break strong reference cycles between objects, where one object has a strong reference to another, and that object in turn has a strong reference back.

Main characteristics of weak:

  • Does not increase the reference count: Using weak does not increase the number of strong references to an object.
  • Can be nil: A weak reference is optional (Optional) and automatically becomes nil when the object it references is deinitialized.
  • Used for parent/child relationships: Often used when a child object has a reference to its parent to avoid strong reference cycles.
  • Requires declaration as var: Since a weak reference can become nil, it must be a variable (var), not a constant (let).

Example of usage:

class Person {
    let name: String
    var apartment: Apartment?

    init(name: String) {
        self.name = name
        print("\(name) is being initialized")
    }

    deinit {
        print("\(name) is being deinitialized")
    }
}

class Apartment {
    let unit: String
    weak var tenant: Person? // Weak reference

    init(unit: String) {
        self.unit = unit
        print("Apartment \(unit) is being initialized")
    }

    deinit {
        print("Apartment \(unit) is being deinitialized")
    }
}

Without weak var tenant: Person? in the Apartment class, there would be a strong reference cycle, and instances of Person and Apartment would not be deinitialized when there are no more strong references to them. Thanks to weak, when a Person instance is deinitialized, the tenant reference in the Apartment instance automatically becomes nil.

What is the weak memory modifier in Swift? — iOS - sobes.tech