0
0
Swiftprogramming~5 mins

Weak self and unowned self patterns in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of using weak self in Swift closures?

Using weak self prevents strong reference cycles by creating a weak reference to self inside a closure. This means the closure does not keep self alive, avoiding memory leaks.

Click to reveal answer
intermediate
How does unowned self differ from weak self in Swift?

unowned self is a non-optional reference that assumes self will always exist when the closure runs. Unlike weak self, it does not become nil. Use it when self is guaranteed to outlive the closure.

Click to reveal answer
beginner
What happens if you access self inside a closure without weak or unowned?

Accessing self strongly inside a closure creates a strong reference cycle if self also holds the closure. This causes a memory leak because neither can be released.

Click to reveal answer
intermediate
When should you use weak self instead of unowned self?

Use weak self when self might become nil before the closure finishes. This makes self optional inside the closure, so you must safely unwrap it.

Click to reveal answer
beginner
Explain a real-life analogy for weak and unowned references.

Imagine self is a person and the closure is a friend holding a photo. weak means the friend holds a photo that can fade (become nil) if the person leaves. unowned means the friend holds a photo that never fades because the person is always around.

Click to reveal answer
What does weak self create inside a closure?
AA weak, optional reference to self
BA strong reference to self
CA non-optional unowned reference to self
DA copy of self
When should you use unowned self in a closure?
AWhen you want to copy self
BWhen self might be nil during closure execution
CWhen self is guaranteed to exist during closure execution
DWhen you want to create a strong reference cycle
What risk do you take when using unowned self incorrectly?
ACrash due to accessing nil reference
BMemory leak
CSlower performance
DNo risk at all
Which keyword makes self optional inside a closure?
Astrong
Bunowned
Clet
Dweak
Why do we avoid strong references to self inside closures?
ATo improve code readability
BTo prevent strong reference cycles and memory leaks
CTo make code run faster
DTo copy self
Explain the difference between weak self and unowned self in Swift closures.
Think about whether self can be nil or not during closure execution.
You got /4 concepts.
    Describe a situation where using weak self is necessary to avoid a memory leak.
    Consider when self and closure keep each other alive.
    You got /4 concepts.