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
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:
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:
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.
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 = nilMai 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.
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:
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 = nilFinished 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 onselfshould capture[weak self].
Test yourself
When does ARC free a class instance?
- When the program ends
- When its strong reference count reaches zero
- Every few seconds
- When you call
free()
What happens to a weak var when the object it refers to is freed?
- It crashes
- It becomes
nil - It keeps the object alive
- It points to a new object
Why write [weak self] in a closure stored on self?
- To make the closure faster
- To avoid a strong reference cycle between the object and the closure
- Because
selfis not available otherwise - To make the closure escaping