Describe the lifecycle of an object in Swift.
Phases (per the runtime's RefCount.h)
- Live — strong RC > 0. All reference kinds work.
- Deiniting — strong RC dropped to 0,
deinitis running. Already in this phase reading aweakreturnsniland reading anunownedtraps. The object cannot be "resurrected": storingselffromdeinitinto a strong variable is a bug. - Deinited —
deinitfinished, fields destroyed, but the memory is not freed while unowned RC > 0 (unowned references must see a deterministic trap, not garbage). - Freed — unowned RC = 0, memory returned to the allocator. If there is a side table, it is still alive.
- 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