Coding/Learn/swift/swift arc and memory management
Swift Foundational Course
01.Introduction, Safety Philosophy & The Toolchain
02.Constants (let), Variables (var) & Type Inference
03.Strings, String Interpolation & Multiline Literals
04.Operators, Range Types & Nil-Coalescing
05.Control Flow: If, Switch Pattern Matching & Guard Statements
06.Optionals, Optional Binding & Optional Chaining
07.Arrays, Sets & Higher-Order Collection Operations
08.Dictionaries, Default Lookups & Tuples
09.Loops, Defer Execution & Labeled Statements
10.Functions, Argument Labels & In-Out Parameters
11.Closures, Trailing Closures & Shorthand Arguments
12.Enums, Raw Values & Associated Values (Tagged Unions)
13.Error Handling: Throwing Functions, Do-Catch & Try Options
14.Structures (struct), Value Semantics & Mutating Methods
15.Classes, Reference Semantics & Inheritance
16.Automatic Reference Counting (ARC), Weak & Unowned References
17.Properties: Stored, Computed, Observers (didSet) & Lazy
18.Protocols, Protocol Extensions & POP (Protocol-Oriented Programming)
19.Generics, Type Constraints & Associated Types
20.Capstone: Production Async/Await Cache & JSON API Engine
Course Certificate0%

Complete all lessons to earn

LearnAutomatic Reference Counting (ARC), Weak & Unowned References
16 / 20 0%
Lesson 16 of 20
10 mins read

Automatic Reference Counting (ARC), Weak & Unowned References

PreviousNext Lesson
In Plain English

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.

The Mental Model

"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.

PointCore Rules to Remember

Point star
Deterministic Deallocation: Unlike Java/Go tracing garbage collection, ARC deallocates memory immediately the moment reference count hits zero.
Point star
weak is Always Optional: weak variables must be mutable optionals (weak var) because ARC sets them to nil upon deallocation.
Point star
Closure Capture Lists: Use [weak self] inside closures to prevent closures from creating retain cycles with their owning view controllers or models.

Common Beginner Traps & How to Fix Them

Mistake: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.

Pro Tip: Use [weak self] in asynchronous escaping closures: guard let self else { return } to safely unwrap self inside the callback.

Live Interactive Example

Hit Run Code to see it live
Breaking Retain Cycles with Weak References
Swift 5.10 / LLVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Output Console
Click "Run Code" to view the rendered output.
How it works: weak var apartment broke the retain cycle, allowing both instances to run their deinit blocks.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Declare a Weak Delegate Reference

  • PointCreate a class TaskEngine with a property weak var delegate: TaskDelegate?.
  • PointCreate a class TaskDelegate with deinit { print("Delegate deallocated") }.
  • PointIn a do scope, create instances, assign the delegate, and verify deinit prints when exiting the scope.
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates