Recall & Review
beginner
What is a strong reference cycle in Swift classes?
A strong reference cycle happens when two or more class instances hold strong references to each other, so neither can be deallocated, causing a memory leak.Click to reveal answer
beginner
Why do strong reference cycles cause memory leaks?
Because the instances keep each other alive by holding strong references, their memory is never freed even if they are no longer needed.
Click to reveal answer
intermediate
How can you break a strong reference cycle between two classes in Swift?
You can use weak or unowned references for one side of the relationship to avoid keeping a strong hold and allow deallocation.
Click to reveal answer
intermediate
What is the difference between weak and unowned references in Swift?
Weak references are optional and become nil when the instance is deallocated. Unowned references are non-optional and assume the instance will always exist during their use.
Click to reveal answer
beginner
Show a simple example of a strong reference cycle between two classes.
class Person {
var apartment: Apartment?
}
class Apartment {
var tenant: Person?
}
Here, Person and Apartment hold strong references to each other, causing a cycle.Click to reveal answer
What happens when two Swift class instances hold strong references to each other?
✗ Incorrect
Strong references keep instances alive. When two instances strongly reference each other, neither can be deallocated, causing a memory leak.
Which keyword in Swift helps to avoid strong reference cycles by not increasing the reference count?
✗ Incorrect
The 'weak' keyword creates a reference that does not increase the reference count, helping to break strong reference cycles.
What is true about unowned references in Swift?
✗ Incorrect
Unowned references are non-optional and assume the instance they point to will not be deallocated while they exist.
If you have a class A with a strong reference to class B, how should class B reference class A to avoid a cycle?
✗ Incorrect
Using weak or unowned references on one side breaks the strong reference cycle and allows memory to be freed.
What happens to a weak reference when the instance it points to is deallocated?
✗ Incorrect
Weak references are optional and automatically become nil when the referenced instance is deallocated.
Explain what a strong reference cycle is and why it is a problem in Swift classes.
Think about how two objects keep each other alive.
You got /3 concepts.
Describe how to use weak and unowned references to fix strong reference cycles with examples.
Focus on how these keywords change reference counting.
You got /4 concepts.