0
0
Swiftprogramming~20 mins

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

Choose your learning style9 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.