DevPrep

All topics › Memory management

Describe the lifecycle of an object in Swift.

Senior PRO

Phases (per the runtime's RefCount.h)

  1. Live — strong RC > 0. All reference kinds work.
  2. Deiniting — strong RC dropped to 0, deinit is running. Already in this phase reading a weak returns nil and reading an unowned traps. The object cannot be "resurrected": storing self from deinit into a strong variable is a bug.
  3. Deinited — deinit finished, fields destroyed, but the memory is not freed while unowned RC > 0 (unowned references must see a deterministic trap, not garbage).
  4. Freed — unowned RC = 0, memory returned to the allocator. If there is a side table, it is still alive.
  5. Dead — weak RC = 0, side table freed. The object exists nowhere anymore.

If nobody ever took a weak to the object, there is no side table and phases 4–5 collapse into one.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store