27.1 · Objects, closures and weak references

Most “what does this print?” questions on memory are really about when: when an object dies, when a closure reads a variable, and when a weak reference is turned back into a strong one.

Mental model. Ask three things of every snippet: what holds a strong reference, does the closure copy the value or share the variable, and when does the code actually run.

Lifetimes and captures

Subclass teardown order, closures in loops, and weak self used step by step.

  1. In what order do initialisers and deinitialisers run for a subclass with stored properties, and what does this print? 27.1.1 · L2
    Initialisation is two-phase and goes up: the subclass first gives every one of its own stored properties a value (here b, which prints “init part…
  2. What do closures print when they capture a loop variable, a shared variable, or a copy in a capture list? 27.1.2 · L2
    A closure captures a variable, not a snapshot of its value, unless you write a capture list. In for i in 0..<3 each iteration has its own fresh constant i, so…
  3. A closure uses [weak self] and the owner is released while the work is running. What is the difference between self?.a(); self?.b() and a guard let self at the top? 27.1.3 · L3
    Each self?.method() is its own “turn a weak reference into a strong one for this one call”. Between two such calls nothing holds the object, so if the last…

More in Puzzles