iOS Developer interview question
How do you avoid retain cycles in Swift?
ARC cannot break a cycle of strong references, so use weak when the referenced object may become nil or unowned only when lifetimes guarantee validity; closures often need an intentional capture list.
Direct answer
What a strong answer covers
How it works
ARC frees an object when its strong reference count reaches zero, so two objects that hold strong references to each other, or an object whose closure captures self strongly while the object stores the closure, are never freed. The fix is to make one side non-owning: weak when the reference may legitimately become nil and is declared optional, unowned when the referenced object is guaranteed to outlive the reference and the crash on misuse is acceptable. Closures need an explicit capture list because they capture self strongly by default.
Example
A view controller that stores a completion handler from a network client and writes self.label.text inside it creates a cycle until the closure declares [weak self] and unwraps it. A parent-child pair such as a Document and its Page uses a strong reference downward and weak upward so deleting the document frees the pages.
Common mistakes
- Sprinkling [weak self] on every closure, including ones that are not stored anywhere.
- Using unowned for an object that can be deallocated first and crashing at runtime.
- Assuming Swift structs or Combine subscriptions cannot participate in a cycle.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.