How ARC frees memory in Swift
ARC is how Swift decides when a class instance is no longer needed. The idea to keep: an instance lives as long as at least one strong reference points to it.
The short version
Swift tracks how many properties, constants and variables currently hold a strong reference to each class instance. When the last one lets go, Swift frees the instance, and its deinit runs just before. This applies only to classes; structs and enums are value types and are not counted.
Step by step
- Assigning a new instance to a variable gives it one strong reference.
- Each extra constant, variable or property that holds it adds one.
- Setting a reference to
niltakes one away. - At zero,
deinitruns and the instance is freed. - If two instances hold each other strongly, neither count reaches zero, so neither is freed. That is a strong reference cycle.
Why it matters
ARC frees memory for you, but it cannot break a cycle by itself; you do, by making one side weak (optional, and set to nil when the instance is freed) or unowned (not optional, and a run-time error if used after the instance is gone). ARC saves you from freeing by hand, but how the instances relate to each other is still your design.
Sources
- Automatic Reference Counting — The Swift Programming Language — counting strong references, classes only, the three-variable example, reference cycles,
weakandunowned - Deinitialization — The Swift Programming Language —
deinitis called immediately before an instance is freed