Recall & Review
beginner
What is an unowned reference in Swift?
An unowned reference is a non-owning pointer to an instance that is expected to always have a valid value during its lifetime. It does not increase the reference count and assumes the referenced object will not be deallocated while the unowned reference exists.
Click to reveal answer
intermediate
How does an unowned reference differ from a weak reference?
An unowned reference assumes the referenced object will never be nil during its lifetime, so it is non-optional and does not become nil automatically. A weak reference is optional and automatically becomes nil when the referenced object is deallocated.
Click to reveal answer
beginner
When should you use unowned references?
Use unowned references when you know the referenced object will always outlive the reference, such as in parent-child relationships where the child references the parent but the parent owns the child.
Click to reveal answer
intermediate
What happens if you access an unowned reference after the referenced object is deallocated?
Accessing an unowned reference after the referenced object is deallocated causes a runtime crash because the reference points to invalid memory.
Click to reveal answer
beginner
Example: How do you declare an unowned reference in Swift?
You declare an unowned reference using the keyword <code>unowned</code> before the variable, for example: <br><pre>class Child {
unowned let parent: Parent
init(parent: Parent) {
self.parent = parent
}
}</pre>Click to reveal answer
What keyword declares an unowned reference in Swift?
✗ Incorrect
The keyword
unowned declares a reference that does not increase the reference count and assumes the referenced object will always exist.Which statement about unowned references is true?
✗ Incorrect
Unowned references do not increase the reference count and are non-optional, assuming the object will always be valid.
When is it safe to use an unowned reference?
✗ Incorrect
Unowned references are safe only if the referenced object will outlive the reference, preventing dangling pointers.
What happens if you access an unowned reference after its object is deallocated?
✗ Incorrect
Accessing an unowned reference after deallocation causes a runtime crash due to invalid memory access.
Which of these is a typical use case for unowned references?
✗ Incorrect
A child referencing its parent with an unowned reference avoids strong reference cycles when the parent owns the child.
Explain what an unowned reference is and when you should use it in Swift.
Think about parent-child relationships and memory safety.
You got /5 concepts.
Describe the difference between unowned and weak references and why that difference matters.
Consider what happens if the referenced object is deallocated.
You got /5 concepts.