How ARC frees memory in Swift

· 2 min read

#how-it-works#apple-dev

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.

How ARC counts strong references Three variables, reference1, reference2 and reference3, each hold a strong reference to one Person instance, so its strong count is 3. When all three are set to nil the count reaches 0 and the instance is freed after its deinit runs. reference1 reference2 reference3 Person instance strong count: 3 deinit runs count reaches 0 all set to nil
Simplified: three variables hold one instance; the instance is freed only when the last of them lets go.

Step by step

  1. Assigning a new instance to a variable gives it one strong reference.
  2. Each extra constant, variable or property that holds it adds one.
  3. Setting a reference to nil takes one away.
  4. At zero, deinit runs and the instance is freed.
  5. 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