0
0
Swiftprogramming~5 mins

Weak references to break cycles in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a strong reference cycle in Swift?
A strong reference cycle happens when two or more objects hold strong references to each other, preventing them from being deallocated and causing a memory leak.
Click to reveal answer
beginner
How does a weak reference help break a strong reference cycle?
A weak reference does not increase the reference count of an object. This allows one object to refer to another without preventing it from being deallocated, thus breaking the cycle.
Click to reveal answer
beginner
In Swift, how do you declare a weak reference?
You declare a weak reference by using the keyword weak before the property declaration, like weak var delegate: SomeDelegate?.
Click to reveal answer
intermediate
Why must weak references be optional in Swift?
Because the referenced object can be deallocated at any time, weak references must be optional to allow them to become nil automatically when the object is gone.
Click to reveal answer
intermediate
What happens if you use a strong reference instead of a weak reference in a delegate pattern?
Using a strong reference in a delegate pattern can create a strong reference cycle between the delegate and the delegator, causing both to stay in memory and leading to a memory leak.
Click to reveal answer
What keyword do you use in Swift to declare a weak reference?
Aweak
Bstrong
Cunowned
Dvar
Why must weak references be optional in Swift?
ABecause they are constants
BBecause they always hold a value
CBecause they increase the reference count
DBecause they can become nil when the referenced object is deallocated
What problem does a strong reference cycle cause?
AMemory leak by preventing deallocation
BFaster program execution
CAutomatic deallocation
DSyntax errors
Which of these is NOT a way to break a strong reference cycle?
AUsing weak references
BUsing strong references everywhere
CUsing unowned references
DSetting references to nil
In a delegate pattern, what kind of reference should the delegate property usually have?
AUnowned reference
BStrong reference
CWeak reference
DConstant reference
Explain what a strong reference cycle is and how weak references help to solve it in Swift.
Think about how objects keep each other alive and how weak references avoid that.
You got /5 concepts.
    Describe how to declare a weak reference in Swift and why it must be optional.
    Focus on the syntax and behavior of weak references.
    You got /4 concepts.