Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 146 ยท Structures, Classes and Enums

Memory Management with ARC

Understand Swift ARC step by step - reference counts, deinit, strong, weak and unowned references, retain cycles, closure capture lists and how to detect leaks, with runnable examples.

Every object you create takes memory, and somebody has to give it back. Languages solve this in different ways: C makes you call free, Java and Kotlin run a garbage collector in the background, and Swift uses ARC, Automatic Reference Counting. ARC is deterministic: an object is destroyed at a precise, predictable moment, right when the last reference to it goes away. No pauses, no manual free.

ARC only applies to class instances (and closures and actors). Structs and enums are values that live where you put them and disappear with their owner. Most of the time you never think about ARC. This lesson is about the times you must: knowing when an object dies, using deinit, and avoiding the classic bug, the retain cycle, where two objects keep each other alive forever.

How reference counting works

Each class instance carries a counter of the strong references pointing to it. Creating a reference (assigning it to a variable, property, array element or capturing it in a closure) adds one. Dropping a reference subtracts one. When the count reaches zero, Swift runs the instance's deinit and frees its memory immediately.

Swift deinit shows when an object dies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Follow the count: after the first line there is 1 reference; copying first into second makes 2; clearing first leaves 1, so the object survives; clearing second makes 0 and the deinit runs before the next line executes. Only classes have deinit, you never call it yourself, and it takes no parameters.

Scope also releases objects

A local variable owns its reference until the end of its scope, and Swift is allowed to release it as early as its last use. This makes deinit useful for releasing resources (closing files, cancelling timers), but do not depend on very precise timing inside one scope.

Swift Objects released at the end of a scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Because deinit can run at slightly different points when the optimizer is on, use it for cleanup and logging, not for program logic that depends on exact order within one function.

Strong references and retain cycles

By default every reference is strong: it keeps its target alive. That is perfect until two objects point at each other. Then each keeps the other's count above zero, and neither is ever freed even after your code has dropped every outside reference. That is a memory leak, called a retain cycle.

Swift A retain cycle (the deinit never runs)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

When publish() returns, the local variables vanish, but the author still holds the book in its books array and the book still holds the author in author. Neither deinit line is ever printed: both objects leak.

weak and unowned references

To break a cycle, make one side of the relationship non-owning. Swift gives you two ways.

  • weak: does not add to the count. The reference becomes nil automatically when the target dies. It must be optional (and a var, or a let in Swift 6.2+).
  • unowned: also does not add to the count, but is never nil. You promise the target outlives you. If you are wrong, the program crashes when you use it.

Fixing the example with weak:

Swift weak breaks the cycle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The author owns the books; the book merely looks at its author. When publish() returns, the only strong reference to the author (the local author) disappears, the author is freed (taking its books array with it), and the book's weak reference turns into nil. The book itself survives because the global book still owns it. The rule of thumb: parents own children strongly, children point at parents weakly.

weak must be optional

The target can disappear at any time, so the type must be able to hold nil:

Swift A non-optional weak property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The error is 'weak' variable should have optional type 'Node?'. Declare it weak var parent: Node?.

Older Swift required weak to be a var. Since Swift 6.2 you may also write weak let when the reference is set once in the initializer; it still becomes nil when the target dies, but nobody can reassign it:

Swift weak let (Swift 6.2 and later)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Choosing unowned

Use unowned when the other object always exists as long as you do and nil would make no sense. A classic example is a credit card that cannot exist without its customer.

Swift unowned: the card never outlives its customer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Setting customer = nil frees the customer, which releases the card, so you see both deinit lines. If some other code kept a reference to the card and used card.customer after the customer was gone, the program would trap with a crash. If you cannot guarantee the lifetime, use weak and handle the nil.

Closures and capture lists

A closure that uses self captures it strongly. If the object also stores the closure, you have a cycle: object -> closure -> object.

Swift A closure cycle, then the capture-list fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Only safe is freed at the end of its block. The capture list [weak self] turns the captured self into an optional weak reference; guard let self else { return } unwraps it for the rest of the closure. Use [unowned self] only when the closure can never outlive the object.

A capture list can also copy a value at the moment the closure is created, instead of sharing a variable:

Swift Capturing a value with a capture list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Not every closure needs [weak self]. A non-escaping closure (such as the one you pass to map) cannot create a cycle, because nobody keeps it. Reach for the capture list when an escaping closure is stored in something the object owns. More on escaping closures in Escaping and Autoclosure.

Structs, actors and ARC

Structs are copied rather than shared, so they cannot form reference cycles by themselves, but a struct that contains a class reference still shares that object. See Value vs. Reference Semantics. Actors are reference types and use ARC like classes. Swift 5.9 added consume and borrowing for fine ownership control; see Noncopyable Types.

Finding leaks in practice

  1. Put a print in deinit of suspect classes and check that it appears when you expect.
  2. Draw the ownership arrows: any loop of strong arrows is a leak.
  3. Delegates, parent pointers, observers and stored closures are the usual suspects: make the non-owning side weak.
  4. Tools such as Xcode's Memory Graph and Instruments find leaks on Apple platforms; on Linux use the same deinit technique.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does Swift run an object's deinit?

    ARC frees an instance immediately when its strong reference count reaches zero, and deinit runs just before. You never call deinit yourself.
  2. 2. What is a retain cycle?

    When A strongly holds B and B strongly holds A, neither can be freed, even if nothing else references them.
  3. 3. How is weak different from unowned?

    Weak references are optional and zero out when the target dies. Unowned references assume the target outlives them and crash if that assumption is wrong.
  4. 4. Which line breaks the cycle in a stored closure that uses the owning object?

    A capture list with weak self makes the closure hold the object weakly, so it no longer keeps it alive.
  5. 5. Which types are managed by ARC?

    ARC counts references to class instances. Value types are copied and live and die with their owner.

Summary

  • ARC counts strong references to class instances and frees them when the count hits zero, running deinit.
  • Use deinit for cleanup and for diagnosing leaks; never call it yourself.
  • Two objects holding each other strongly form a retain cycle and leak.
  • weak var (optional, becomes nil) and unowned (never nil, crashes if wrong) break cycles; owners hold strongly, back-references weakly.
  • Escaping closures stored by the object they capture need [weak self] (or [unowned self]).
  • Capture lists can also freeze a value: [counter].

Next: Inheritance