Swift & Concurrency (50 Qs)•Part 3: Runtime Internals, Swift 6 Safety & Systems Programming (25 - 35)
ARC Memory Management: Strong, Weak, Unowned, and resolving Retain Cycles.
senior LevelswiftRuntime Internals
In Simple Words: Automatic Reference Counting (ARC) automatically tracks and manages memory:
- Strong Reference: Increments retain count. Object stays in memory as long as retain count $> 0$.
- Weak Reference: Does not increment retain count. Automatically sets pointer to
nilwhen target object deallocates (always an optionalweak var). - Unowned Reference: Does not increment retain count. Assumes the target will never be nil during the pointer's lifetime. Accessing after deallocation crashes with a memory fault.
- Closure Retain Cycle Fix: Always capture
[weak self]when a closure is retained by an instance property or callback listener.