0
0
Swiftprogramming~5 mins

Strong reference cycles between classes in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AThey create a strong reference cycle causing a memory leak.
BThey automatically deallocate each other.
CThey become weak references.
DThey convert to value types.
Which keyword in Swift helps to avoid strong reference cycles by not increasing the reference count?
Astrong
Bstatic
Cweak
Dfinal
What is true about unowned references in Swift?
AThey are non-optional and assume the referenced instance always exists.
BThey cause strong reference cycles.
CThey increase the reference count.
DThey are optional and can become nil.
If you have a class A with a strong reference to class B, how should class B reference class A to avoid a cycle?
AWith a strong reference.
BWith a weak or unowned reference.
CWith a static reference.
DWith a global variable.
What happens to a weak reference when the instance it points to is deallocated?
AIt converts to an unowned reference.
BIt crashes the program.
CIt keeps pointing to invalid memory.
DIt becomes nil automatically.
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.