Bird
Raised Fist0
Swiftprogramming~20 mins

Unowned references for guaranteed lifetime in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Unowned Reference Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of unowned reference usage in Swift
What is the output of this Swift code using an unowned reference?
Swift
class Owner {
    var name: String
    init(name: String) { self.name = name }
    deinit { print("Owner \(name) is being deinitialized") }
}

class Dependent {
    unowned let owner: Owner
    init(owner: Owner) { self.owner = owner }
    func printOwnerName() {
        print("Owner's name is \(owner.name)")
    }
}

var owner: Owner? = Owner(name: "Alice")
var dependent: Dependent? = Dependent(owner: owner!)
dependent?.printOwnerName()
owner = nil
print("End of program")
A
Owner's name is Alice
Owner Alice is being deinitialized
End of program
BRuntime error: accessing deinitialized owner
C
Owner Alice is being deinitialized
Owner's name is Alice
End of program
D
Owner's name is Alice
End of program
Attempts:
2 left
💡 Hint
Think about when the deinitializer runs and when the unowned reference is accessed.
❓ Predict Output
intermediate
2:00remaining
What happens if unowned reference is accessed after owner is nil?
What error occurs when accessing an unowned reference after its owner is deallocated?
Swift
class Owner {
    var name: String
    init(name: String) { self.name = name }
    deinit { print("Owner \(name) deinitialized") }
}

class Dependent {
    unowned let owner: Owner
    init(owner: Owner) { self.owner = owner }
    func printOwnerName() {
        print("Owner's name is \(owner.name)")
    }
}

var owner: Owner? = Owner(name: "Bob")
var dependent: Dependent? = Dependent(owner: owner!)
owner = nil
// Now accessing dependent.owner
dependent?.printOwnerName()
A
Owner Bob deinitialized
Runtime error: unexpectedly found nil while unwrapping an Optional value
B
Owner Bob deinitialized
Owner's name is Bob
C
Owner Bob deinitialized
Runtime error: accessing deallocated memory
D
Owner Bob deinitialized
No output
Attempts:
2 left
💡 Hint
Unowned references do not become nil automatically. What happens if you access them after deallocation?
🔧 Debug
advanced
2:30remaining
Identify the cause of runtime crash with unowned reference
Why does this Swift code crash at runtime?
Swift
class Person {
    let name: String
    unowned var apartment: Apartment
    init(name: String, apartment: Apartment) {
        self.name = name
        self.apartment = apartment
    }
}

class Apartment {
    let unit: String
    var tenant: Person?
    init(unit: String) {
        self.unit = unit
    }
}

var apt: Apartment? = Apartment(unit: "4B")
var person: Person? = Person(name: "John", apartment: apt!)
apt?.tenant = person
apt = nil
person?.apartment.unit
ACompile-time error: unowned property must be initialized before use
BNo output, code runs fine
CRuntime error: accessing deallocated apartment via unowned reference
DRuntime error: unexpected nil while unwrapping Optional
Attempts:
2 left
💡 Hint
Consider the lifetime of apartment and how unowned references behave when the referenced object is deallocated.
🧠 Conceptual
advanced
1:30remaining
Why use unowned references instead of weak references?
Which statement best explains when to use unowned references instead of weak references in Swift?
AUse unowned references only for value types like structs and enums.
BUse unowned references when the referenced object might become nil and you want to handle that safely.
CUse unowned references to create strong reference cycles intentionally.
DUse unowned references when the referenced object is guaranteed to have a longer lifetime than the reference, avoiding optional unwrapping.
Attempts:
2 left
💡 Hint
Think about the difference between optional and non-optional references and lifetime guarantees.
❓ Predict Output
expert
2:30remaining
Count of items in dictionary with unowned references as keys
What is the number of items in the dictionary after this Swift code runs?
Swift
class Item {
    let id: Int
    init(id: Int) { self.id = id }
    deinit { print("Item \(id) deinitialized") }
}

var dict: [Unowned<Item>: String] = [:]

var item1: Item? = Item(id: 1)
var item2: Item? = Item(id: 2)

dict[Unowned(item1!)] = "First"
dict[Unowned(item2!)] = "Second"

item1 = nil

print(dict.count)
ARuntime error: cannot use unowned reference as dictionary key
B2
C0
D1
Attempts:
2 left
💡 Hint
Consider that unowned references do not affect reference counting and dictionary keys remain until explicitly removed.

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

  1. Step 1: Understand what unowned means

    unowned references do not increase the lifetime of the object they point to.
  2. 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.
  3. Final Answer:

    To refer to another object without increasing its lifetime -> Option D
  4. 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

  1. Step 1: Recall Swift syntax for unowned references

    The correct syntax places unowned before the variable declaration: unowned var variableName: Type.
  2. Step 2: Match the options

    unowned var friend: Person matches this syntax exactly: unowned var friend: Person.
  3. Final Answer:

    unowned var friend: Person -> Option A
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    true -> Option A
  4. 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

  1. Step 1: Understand the unowned reference lifetime

    The unowned reference b in class A assumes B instance exists as long as A exists.
  2. 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.
  3. Final Answer:

    Unowned reference b is accessed after B is deallocated -> Option B
  4. 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

  1. Step 1: Understand the lifetime relationship

    The Teacher owns the Student strongly, so the Teacher will exist as long as the Student does.
  2. 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.
  3. Final Answer:

    Because the Teacher always exists as long as the Student exists, preventing strong reference cycles -> Option C
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard