How ARC works

Memory & ARC Junior Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Predict the output

What is the print order?

final class Node {
    let name: String
    init(_ name: String) { self.name = name }
    deinit { print("deinit \(name)") }
}
var a: Node? = Node("A")
var b = a
a = nil
print("after a")
b = nil
print("after b")
Options
Hint 1 of 1

How many strong references exist after a = nil?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: B after a, deinit A, after b

Correct. The count drops to zero only when b is set to nil.

Why not the others?
  • A deinit A, after a, after b. b still holds a strong reference after a = nil.
  • C after a, after b, deinit A. deinit runs immediately when the last strong reference goes away.
  • D after a, after b, and deinit never runs. There is no cycle, so the object is freed.

30-second answer

ARC counts the strong references to each class instance. The compiler inserts retain and release calls; when the count reaches zero, deinit runs and the memory is freed immediately. It is deterministic, unlike garbage collection, but it can't free objects that reference each other strongly, which is a retain cycle.

Practise saying it · 30 s. No recording, just a timer

Explain how ARC works.

Say your answer out loud, then check which of these points you covered:

  • Counts strong references
  • Frees at zero, deterministically
  • Can't break cycles

Deep dive

Only reference types (classes, actors, closures) are reference counted.

weak and unowned references don't increase the strong count.

The optimizer may release an object right after its last use, earlier than the end of scope.

Use withExtendedLifetime if an object must stay alive until a point.

Common mistakes

  • Thinking ARC runs periodically like a garbage collector.
  • Relying on an object living until the end of a scope.

Senior take & follow-ups

Seniors call ARC deterministic and immediately explain where it fails: cycles.

Follow-up questions

Think of your answer first, then open the hint.

  1. When can an object be freed before scope end?

    Show hint

    After its last use, because the optimizer may shorten lifetimes.

  2. Does ARC manage structs?

    Show hint

    No, but class references inside structs are counted.

Suggest a fix if something here is wrong or out of date.