Swift manages heap memory for class instances with Automatic Reference Counting (ARC)—deterministic deallocation when reference count hits zero, unlike tracing GC in Java or Go.
Reference cycles
class Node {
var next: Node?
deinit { print("deinit") }
}
Strong references between classes can leak—break cycles with weak or unowned references, especially in closures capturing self.
Value types and ARC
Structs and enums do not use ARC for their own storage—copy-on-write collections may share buffers until mutated.
Important interview questions and answers
- Q: weak vs unowned?
A:weakis optional and zeroes when target deallocates;unownedassumes target outlives the reference—crash if wrong. - Q: Struct on stack?
A: Small value types often live on the stack or inline; classes always heap-allocate instance data with ARC tracking.
Self-check
- What memory model do Swift classes use?
- How do closures cause retain cycles?
Pitfall: Closures capturing self strongly can create retain cycles—use [weak self] in class contexts.
Interview prep
- weak vs unowned?
weak optional and zeroes; unowned assumes target outlives reference.
- Retain cycles?
Strong references between classes or closures capturing self strongly.