Swift Tutorial · Advanced Swift · Lesson 25 of 30
Swift Memory Management: ARC and weak References
How automatic reference counting works, retain cycles, and breaking them with weak and unowned.
Automatic Reference Counting
Swift frees a class instance when the last strong reference to it goes away, and calls its deinit. There's
no garbage collector, so this happens at a predictable moment.
final class Connection {
let name: String
init(name: String) { self.name = name; print("open \(name)") }
deinit { print("close \(name)") }
}
do {
let db = Connection(name: "db")
var other: Connection? = db // a second strong reference
print("using \(db.name)")
other = nil
print("still open: other reference dropped")
_ = other
}
print("after the scope")
Output
open db using db still open: other reference dropped close db after the scope
Run this on your computer — see “Get Started” for setup.
Retain cycles
If two objects hold strong references to each other (or a closure captures self strongly), neither is ever
freed. Make one side weak (it becomes nil when the object is freed) or capture [weak self] in closures.
final class Owner {
let name: String
var pet: Pet?
init(name: String) { self.name = name }
deinit { print("\(name) freed") }
}
final class Pet {
weak var owner: Owner? // weak: doesn't keep the owner alive
deinit { print("pet freed") }
}
do {
let ana = Owner(name: "Ana")
let cat = Pet()
ana.pet = cat
cat.owner = ana
print("cat's owner: \(cat.owner?.name ?? "none")")
}
print("no leak: both deinits ran")
Output
cat's owner: Ana Ana freed pet freed no leak: both deinits ran
Run this on your computer — see “Get Started” for setup.
Test yourself
What happens to a weak reference when the object it points to is freed?
It keeps the object aliveIt becomes nil automaticallyIt crashesIt points to a copy
Show answer
Answer: It becomes nil automatically