Unowned References for Guaranteed Lifetime in Swift
📖 Scenario: Imagine you are building a simple app to manage a library. Each Book has an Author. The Author always exists as long as the Book exists, so you want to link them without creating a strong reference cycle.
🎯 Goal: You will create two classes, Author and Book, and use an unowned reference in Book to refer to its Author. This ensures the Author will always be alive while the Book exists, avoiding memory leaks.
📋 What You'll Learn
Create a class called Author with a name property.
Create a class called Book with a title property and an unowned reference to an Author.
Initialize Book with a title and an Author.
Print the book's title and its author's name.
💡 Why This Matters
🌍 Real World
In real apps, classes often refer to each other. Using <code>unowned</code> references helps manage memory safely when one object always exists as long as the other does.
💼 Career
Understanding memory management and reference types in Swift is important for building efficient iOS apps without memory leaks.
Progress0 / 4 steps
1
Create the Author class
Create a class called Author with a name property of type String. Initialize name using an initializer.
Swift
Hint
Think of Author as a simple class holding the author's name.
2
Create the Book class with an unowned reference
Create a class called Book with a title property of type String and an unowned property called author of type Author. Initialize both properties using an initializer.
Swift
Hint
Use unowned before the author property to avoid strong reference cycles.
3
Create instances of Author and Book
Create an instance of Author named author with the name "Jane Austen". Then create an instance of Book named book with the title "Pride and Prejudice" and the author instance you just created.
Swift
Hint
Create the author first, then pass it to the Book initializer.
4
Print the book title and author name
Print the book's title and its author's name in the format: "Pride and Prejudice by Jane Austen" using the book instance.
Swift
Hint
Use string interpolation to combine book.title and book.author.name.
Practice
(1/5)
1. What is the main purpose of using unowned references in Swift?
easy
A. To automatically nil out the reference when the object is deallocated
B. To create a strong reference that keeps the object alive
C. To make a copy of the referenced object
D. To refer to another object without increasing its lifetime
Solution
Step 1: Understand what unowned means
unowned references do not increase the lifetime of the object they point to.
Step 2: Compare with other reference types
Unlike strong references, unowned does not keep the object alive, and unlike weak references, it assumes the object will always exist during use.
Final Answer:
To refer to another object without increasing its lifetime -> Option D
Quick Check:
Unowned references = no lifetime increase [OK]
Hint: Unowned means no lifetime increase, but object must exist [OK]
Common Mistakes:
Confusing unowned with strong references
Thinking unowned automatically nils out
Assuming unowned copies the object
2. Which of the following is the correct syntax to declare an unowned reference to an instance of class Person named friend?
easy
A. unowned var friend: Person
B. var friend: unowned Person
C. var friend: Person unowned
D. var unowned friend: Person
Solution
Step 1: Recall Swift syntax for unowned references
The correct syntax places unowned before the variable declaration: unowned var variableName: Type.
Step 2: Match the options
unowned var friend: Person matches this syntax exactly: unowned var friend: Person.
Final Answer:
unowned var friend: Person -> Option A
Quick Check:
Unowned keyword before var = correct syntax [OK]
Hint: Put 'unowned' before 'var' for correct syntax [OK]
Common Mistakes:
Placing 'unowned' after the variable name
Using 'var' after 'unowned' incorrectly
Writing 'unowned' after the type
3. Consider the following Swift code snippet:
class Owner {
var pet: Pet?
}
class Pet {
unowned var owner: Owner
init(owner: Owner) {
self.owner = owner
}
}
let owner = Owner()
owner.pet = Pet(owner: owner)
print(owner.pet?.owner === owner)
What will be the output?
medium
A. true
B. false
C. nil
D. Runtime error
Solution
Step 1: Understand the relationship between Owner and Pet
Owner has an optional Pet, and Pet has an unowned reference back to Owner, meaning Pet expects Owner to exist while Pet exists.
Step 2: Analyze the print statement
The print checks if the owner property of pet is the same instance as owner using identity operator ===. Since pet.owner was set to owner, this is true.
Final Answer:
true -> Option A
Quick Check:
Unowned reference points to existing object = true [OK]
Hint: Unowned references assume object exists, so identity check is true [OK]
Common Mistakes:
Thinking unowned makes owner nil
Confusing identity operator with equality
Expecting runtime error due to unowned
4. Given the code below, what is the main issue causing a runtime crash?
class A {
unowned var b: B
init(b: B) {
self.b = b
}
}
class B {
var a: A?
}
var bInstance: B? = B()
var aInstance: A? = A(b: bInstance!)
bInstance?.a = aInstance
bInstance = nil
print(aInstance!.b)
aInstance = nil
medium
A. Optional unwrapping failure
B. Unowned reference b is accessed after B is deallocated
C. Syntax error in unowned declaration
D. Strong reference cycle causing memory leak
Solution
Step 1: Understand the unowned reference lifetime
The unowned reference b in class A assumes B instance exists as long as A exists.
Step 2: Analyze object deallocation order
When bInstance is set to nil, B is deallocated, but A remains alive (held by aInstance). Thus b in A points to deallocated B, and print(aInstance!.b) accesses it, causing crash.
Final Answer:
Unowned reference b is accessed after B is deallocated -> Option B
Quick Check:
Unowned must not outlive referenced object [OK]
Hint: Unowned crashes if referenced object is gone first [OK]
Common Mistakes:
Confusing unowned with weak references
Ignoring object deallocation order
Assuming unowned prevents crashes automatically
5. You have two classes, Teacher and Student, where each Student has an unowned reference to their Teacher, and each Teacher has a strong array of Student instances. Which of the following best explains why using unowned for the Student to Teacher reference is appropriate?
hard
A. Because unowned references automatically nil out when the Teacher is deallocated
B. Because the Student might outlive the Teacher, so unowned avoids nil references
C. Because the Teacher always exists as long as the Student exists, preventing strong reference cycles
D. Because unowned references increase the lifetime of the Teacher to match the Student
Solution
Step 1: Understand the lifetime relationship
The Teacher owns the Student strongly, so the Teacher will exist as long as the Student does.
Step 2: Why use unowned here?
Using unowned for the Student to Teacher reference avoids a strong reference cycle because Student does not keep Teacher alive.
Final Answer:
Because the Teacher always exists as long as the Student exists, preventing strong reference cycles -> Option C
Quick Check:
Unowned = guaranteed lifetime, no cycle [OK]
Hint: Use unowned when referenced object lifetime is guaranteed [OK]
Common Mistakes:
Thinking unowned nils out automatically
Assuming unowned increases lifetime
Using unowned when referenced object may be nil
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.