Python Automatic Reference Counting (ARC), Weak & Unowned References
Swift manages memory automatically using Automatic Reference Counting (ARC). Learn how retain counts work, how strong reference cycles cause memory leaks, and how to resolve retain cycles using weak (optional) and unowned (non-optional) references.
"ARC is like a tally clerk tracking how many people hold a key to a room. As long as at least 1 person holds a key (count > 0), the room stays open. When the last person returns their key (count = 0), the clerk locks and dismantles the room."
Deep Dive: How It Works
How ARC Works: Increments reference count when a new variable references a class instance; decrements count when variables go out of scope.
Strong Retain Cycles: Occurs when Object A strongly references Object B, and Object B strongly references Object A, preventing both from ever reaching count 0.
weak References: Always declared as weak var optObj: ClassName?; does not increment reference count and automatically becomes nil when the target is deallocated.
unowned References: Non-optional reference used when the referenced object is guaranteed to have the same or longer lifetime.
Syntax Blueprint
class Person {
weak var apartment: Apartment?
}
class Apartment {
var tenant: Person?
}Use weak var to break strong reference cycles between interrelated objects.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Using unowned on an object that gets deallocated before the accessor, leading to a crash.Why it happens: Accessing a dangling unowned reference triggers a runtime fatal memory trap.
How to fix: Use weak whenever the referenced instance could potentially become nil.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Declare a Weak Delegate Reference
Create a class TaskEngine with a property weak var delegate: TaskDelegate?.
Create a class TaskDelegate with deinit { print("Delegate deallocated") }.
In a do scope, create instances, assign the delegate, and verify deinit prints when exiting the scope.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.