TExcelTAD
Home › Swift › Memory Management & ARC

Memory Management & ARC

Swift manages the memory of class instances with Automatic Reference Counting (ARC). Every object keeps a count of how many strong references point to it. When that count drops to zero, the object is destroyed immediately and its deinit runs. There is no garbage collector pausing your app — but there is one trap you must learn to avoid: reference cycles.

Note: ARC only applies to reference types (classes, closures, actors). Structs and enums are values: they are copied and freed automatically, with no counting.

Watching ARC at work

swift · try it yourself
class Ticket {
    let id: Int
    init(id: Int) { self.id = id; print("Ticket \(id) created") }
    deinit { print("Ticket \(id) freed") }
}

var a: Ticket? = Ticket(id: 1)   // count = 1
var b = a                        // count = 2
print("two references")

a = nil                          // count = 1
print("a is nil, ticket still alive")

b = nil                          // count = 0 → freed
print("end")
Ticket 1 created
two references
a is nil, ticket still alive
Ticket 1 freed
end

Objects created inside a function are freed when the function returns, unless something keeps a reference:

swift · try it yourself
class Guest {
    let name: String
    init(name: String) { self.name = name }
    deinit { print("\(name) left the party") }
}

func party() {
    let g1 = Guest(name: "Lan")
    let g2 = Guest(name: "Duc")
    print("Party with \(g1.name) and \(g2.name)")
}   // g1 and g2 go out of scope here

party()
print("After the party")
Party with Lan and Duc
Duc left the party
Lan left the party
After the party

Strong reference cycles

If two objects hold strong references to each other, neither count can ever reach zero. They stay in memory forever — a memory leak:

swift · try it yourself
class Person {
    let name: String
    var apartment: Apartment?
    init(name: String) { self.name = name }
    deinit { print("\(name) freed") }
}

class Apartment {
    let unit: String
    var tenant: Person?          // strong!
    init(unit: String) { self.unit = unit }
    deinit { print("Apartment \(unit) freed") }
}

var mai: Person? = Person(name: "Mai")
var flat: Apartment? = Apartment(unit: "4B")
mai?.apartment = flat
flat?.tenant = mai

mai = nil
flat = nil
print("No deinit was printed — both objects leaked.")
No deinit was printed — both objects leaked.

Breaking cycles with weak

A weak reference does not increase the count. When the object it points to is freed, the weak reference automatically becomes nil — so it must always be an optional var.

swift · try it yourself
class Person {
    let name: String
    var apartment: Apartment?
    init(name: String) { self.name = name }
    deinit { print("\(name) freed") }
}

class Apartment {
    let unit: String
    weak var tenant: Person?     // weak: does not keep the person alive
    init(unit: String) { self.unit = unit }
    deinit { print("Apartment \(unit) freed") }
}

var mai: Person? = Person(name: "Mai")
var flat: Apartment? = Apartment(unit: "4B")
mai?.apartment = flat
flat?.tenant = mai

mai = nil
print("tenant is now:", flat?.tenant?.name ?? "nil")
flat = nil
Mai freed
tenant is now: nil
Apartment 4B freed

unowned references

An unowned reference also does not increase the count, but it is not optional: use it when the other object is guaranteed to live at least as long. Accessing an unowned reference after its object was freed crashes, so only use it when the lifetimes are certain.

swift
class Customer {
    var card: CreditCard?
}

class CreditCard {
    unowned let owner: Customer   // a card never outlives its customer
    init(owner: Customer) { self.owner = owner }
}
Reference Increases count? Optional? When the object is freed
strong (default) Yes Either Keeps it alive
weak No Must be optional var Becomes nil
unowned No Usually non-optional Access crashes

Cycles with closures and [weak self]

Closures are reference types too. A class that stores a closure which uses self creates a cycle: object → closure → object. Fix it with a capture list:

swift · try it yourself
class Downloader {
    let file: String
    var onFinish: (() -> Void)?

    init(file: String) { self.file = file }
    deinit { print("Downloader for \(file) freed") }

    func start() {
        onFinish = { [weak self] in
            guard let self else { return }
            print("Finished \(self.file)")
        }
        onFinish?()
    }
}

var job: Downloader? = Downloader(file: "photo.jpg")
job?.start()
job = nil
Finished photo.jpg
Downloader for photo.jpg freed

Remove [weak self] and the deinit line disappears — the downloader would leak.

Tip: Rules of thumb: a parent holds its children strongly, a child refers back to its parent weakly; delegates are usually weak var delegate; escaping closures stored on self should capture [weak self].

Test yourself

When does ARC free a class instance?

  1. When the program ends
  2. When its strong reference count reaches zero
  3. Every few seconds
  4. When you call free()

What happens to a weak var when the object it refers to is freed?

  1. It crashes
  2. It becomes nil
  3. It keeps the object alive
  4. It points to a new object

Why write [weak self] in a closure stored on self?

  1. To make the closure faster
  2. To avoid a strong reference cycle between the object and the closure
  3. Because self is not available otherwise
  4. To make the closure escaping