📖 Scenario: Imagine you are building a simple app that manages a list of books. Each book has a title and an author. You want to understand how Swift manages memory automatically to keep your app running smoothly without crashes or slowdowns.
🎯 Goal: You will create a small Swift program that shows how Automatic Reference Counting (ARC) works by creating and releasing objects. This will help you see why ARC is important for managing memory in Swift apps.
📋 What You'll Learn
Create a class called Book with properties title and author
Create a variable called book1 and assign it a Book instance
Create a second variable called book2 and assign it the same instance as book1
Set book1 to nil and observe that the object is still kept alive by book2
Set book2 to nil and observe that the object is deallocated
💡 Why This Matters
🌍 Real World
Memory management is crucial in apps to keep them fast and stable. ARC helps Swift developers avoid manual memory handling.
💼 Career
Understanding ARC is essential for Swift developers to write efficient, bug-free code and maintain app performance.
Progress0 / 4 steps
1
Create the Book class
Create a class called Book with two properties: title and author, both of type String. Add an initializer to set these properties. Also add a deinit method that prints "Book titled \"\(title)\" is being deallocated".
Swift
Hint
Remember to use deinit to see when the object is removed from memory.
2
Create the first reference to a Book instance
Create a variable called book1 and assign it a new Book instance with the title "Swift Programming" and author "Apple".
Swift
Hint
Use var book1: Book? = Book(title: "Swift Programming", author: "Apple") to create the instance.
3
Create a second reference to the same Book instance
Create a variable called book2 and assign it the same instance as book1.
Swift
Hint
Just assign book2 = book1 to share the same object.
4
Set references to nil and observe deallocation
Set book1 to nil. Then set book2 to nil. This will show when the Book instance is deallocated by ARC.
Swift
Hint
Setting both references to nil lets ARC remove the object and call deinit.
Practice
(1/5)
1. What is the main purpose of Automatic Reference Counting (ARC) in Swift?
easy
A. To automatically manage memory by tracking object references
B. To optimize the speed of Swift code execution
C. To handle user interface layout automatically
D. To compile Swift code into machine language
Solution
Step 1: Understand ARC's role in memory management
ARC tracks how many references point to an object to manage its memory automatically.
Step 2: Differentiate ARC from other tasks
ARC does not optimize speed, handle UI layout, or compile code; it focuses on memory.
Final Answer:
To automatically manage memory by tracking object references -> Option A
Quick Check:
ARC = memory management [OK]
Hint: ARC counts references to manage memory automatically [OK]
Common Mistakes:
Confusing ARC with code compilation
Thinking ARC manages UI layout
Assuming ARC improves execution speed
2. Which of the following is the correct way to declare a weak reference in Swift?
easy
A. var delegate: weak MyDelegate?
B. weak var delegate: MyDelegate?
C. var weak delegate: MyDelegate?
D. var delegate: MyDelegate weak?
Solution
Step 1: Recall Swift syntax for weak references
In Swift, the keyword weak comes before the variable declaration type.
Step 2: Check each option's syntax
weak var delegate: MyDelegate? correctly places weak before var and the type, matching Swift syntax.
Final Answer:
weak var delegate: MyDelegate? -> Option B
Quick Check:
Weak reference syntax = "weak var" [OK]
Hint: Use 'weak var' before the variable name for weak references [OK]
Common Mistakes:
Placing 'weak' after the variable name
Using 'var weak' instead of 'weak var'
Omitting the optional '?' for weak references
3. Consider the following Swift code:
class Person {
var name: String
init(name: String) {
self.name = name
}
}
var person1: Person? = Person(name: "Alice")
var person2 = person1
person1 = nil
print(person2?.name ?? "No name")
What will be printed?
medium
A. Runtime error
B. "No name"
C. nil
D. "Alice"
Solution
Step 1: Understand reference counting in the code
Both person1 and person2 point to the same Person object initially, so reference count is 2.
Step 2: Analyze effect of setting person1 to nil
Setting person1 to nil reduces reference count to 1, but person2 still holds the object.
Step 3: Determine print output
Since person2 still references the object, person2?.name is "Alice".
Final Answer:
"Alice" -> Option D
Quick Check:
Reference count > 0 means object exists [OK]
Hint: Object stays alive if any strong reference exists [OK]
Common Mistakes:
Assuming object is deallocated when one reference is nil
Confusing optional chaining output
Expecting runtime error due to nil assignment
4. Given this Swift code snippet, what is the main problem?
class Node {
var value: Int
var next: Node?
init(value: Int) {
self.value = value
}
}
var first: Node? = Node(value: 1)
var second: Node? = Node(value: 2)
first?.next = second
second?.next = first
medium
A. Syntax error in class definition
B. Runtime crash due to nil unwrapping
C. Strong reference cycle causing memory leak
D. No problem, code runs fine
Solution
Step 1: Identify references between nodes
first points to second, and second points back to first, creating a cycle.
Step 2: Understand ARC impact of strong cycles
Both nodes hold strong references to each other, so ARC cannot deallocate them, causing a memory leak.
Final Answer:
Strong reference cycle causing memory leak -> Option C
Quick Check:
Strong cycles = memory leaks [OK]
Hint: Check for mutual strong references causing leaks [OK]
Common Mistakes:
Thinking this causes syntax errors
Assuming ARC handles cycles automatically
Ignoring possibility of memory leaks
5. You have two classes, Teacher and Student, where each Teacher has a list of Student objects, and each Student has a reference to their Teacher. How should you declare these references to avoid memory leaks caused by ARC?
hard
A. Declare Teacher's students as strong and Student's teacher as weak
B. Declare both references as strong
C. Declare Teacher's students as weak and Student's teacher as strong
D. Declare both references as weak
Solution
Step 1: Identify ownership direction
The Teacher owns the list of Student objects, so this should be a strong reference.
Step 2: Avoid strong cycle by making reverse reference weak
The Student references back to Teacher should be weak to prevent a strong reference cycle.
Final Answer:
Declare Teacher's students as strong and Student's teacher as weak -> Option A
Quick Check:
Strong ownership one way, weak back reference [OK]
Hint: Make back references weak to break strong cycles [OK]
Common Mistakes:
Making both references strong causing leaks
Making both references weak causing premature deallocation
Confusing which side should be weak
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.