0
0
Swiftprogramming~5 mins

Memory implications of captures in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a closure capture in Swift?
A closure capture happens when a closure uses variables or constants from its surrounding context, keeping a reference to them even after the original scope ends.
Click to reveal answer
intermediate
Why can capturing self strongly inside a closure cause memory leaks?
Because the closure keeps a strong reference to self, and if self also holds a reference to the closure, they keep each other alive, causing a retain cycle and memory leak.
Click to reveal answer
intermediate
What is a weak capture in Swift closures?
A weak capture means the closure holds a weak reference to the captured variable, so it does not increase its reference count and helps avoid retain cycles.
Click to reveal answer
beginner
How do you declare a weak capture of self in a Swift closure?
Use a capture list like [weak self] before the closure body, for example: { [weak self] in ... }
Click to reveal answer
advanced
What happens if you use [unowned self] in a closure and self is nil when accessed?
Using [unowned self] means the closure assumes self will never be nil. If self is nil when accessed, the program will crash with a runtime error.
Click to reveal answer
What does a strong capture inside a closure do to the captured variable's reference count?
ADecreases the reference count
BSets the reference count to zero
CDoes not affect the reference count
DIncreases the reference count
Which capture type helps prevent retain cycles by not increasing reference count?
AStrong
BUnowned
CWeak
DStatic
What keyword is used in Swift to declare a weak capture in a closure?
Aweak
Bunowned
Cstatic
Dstrong
What risk comes with using [unowned self] in a closure?
ARuntime crash if self is nil
BMemory leak
CSlower performance
DNo risk at all
Why should you be careful capturing self strongly in closures inside classes?
AIt makes the code slower
BIt can cause retain cycles and memory leaks
CIt causes syntax errors
DIt prevents the closure from running
Explain what a retain cycle is and how closure captures can cause it in Swift.
Think about two objects holding strong references to each other.
You got /4 concepts.
    Describe the difference between weak and unowned captures in Swift closures and when to use each.
    Consider safety and lifetime of the captured variable.
    You got /4 concepts.