Bird
Raised Fist0
Swiftprogramming~20 mins

Memory implications of captures in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Memory Capture Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of closure capturing a class instance
What will be printed when this Swift code runs?
Swift
class Counter {
    var count = 0
    func increment() {
        count += 1
    }
}

func makeIncrementer() -> () -> Void {
    let counter = Counter()
    return {
        counter.increment()
        print(counter.count)
    }
}

let incrementer = makeIncrementer()
incrementer()
incrementer()
A1\n2
B0\n1
C2\n3
D1\n1
Attempts:
2 left
💡 Hint
Think about how the closure captures the Counter instance and modifies it.
❓ Predict Output
intermediate
2:00remaining
Memory leak due to strong reference cycle
What error or behavior will this Swift code cause?
Swift
class Person {
    let name: String
    var apartment: Apartment?
    init(name: String) { self.name = name }
    deinit { print("Person \(name) is being deinitialized") }
}

class Apartment {
    let unit: String
    var tenant: Person?
    init(unit: String) { self.unit = unit }
    deinit { print("Apartment \(unit) is being deinitialized") }
}

var john: Person? = Person(name: "John")
var unit4A: Apartment? = Apartment(unit: "4A")
john!.apartment = unit4A
unit4A!.tenant = john

john = nil
unit4A = nil
ABoth Person and Apartment deinitialized messages printed
BOnly Person deinitialized message printed
CNo deinitialization messages printed (memory leak)
DOnly Apartment deinitialized message printed
Attempts:
2 left
💡 Hint
Consider how strong references between Person and Apartment affect memory.
🔧 Debug
advanced
2:00remaining
Fixing a retain cycle with capture lists
This Swift closure causes a memory leak by capturing self strongly. Which option correctly fixes the leak?
Swift
class ViewController {
    var name = "Main"
    lazy var closure: () -> Void = {
        print(self.name)
    }
    deinit { print("ViewController deinitialized") }
}

var vc: ViewController? = ViewController()
vc?.closure()
vc = nil
Alazy var closure: () -> Void = { [strong self] in print(self.name) }
Blazy var closure: () -> Void = { [weak self] in print(self?.name ?? "No name") }
Clazy var closure: () -> Void = { print(self.name) }
Dlazy var closure: () -> Void = { [unowned self] in print(self.name) }
Attempts:
2 left
💡 Hint
Use capture lists to avoid strong reference cycles. Consider unowned vs weak.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in closure capture
Which option contains a syntax error in the closure capture list?
Alet closure = { [weak self] in print(self?.description) }
Blet closure = { [strong self] in print(self.description) }
Clet closure = { [weak self, unowned delegate] in print(self?.description) }
Dlet closure = { [unowned self] in print(self.description) }
Attempts:
2 left
💡 Hint
Check if the capture list keywords are valid Swift syntax.
🚀 Application
expert
3:00remaining
Analyzing memory behavior of nested closures
Consider this Swift code with nested closures capturing variables. What is the output when calling outer() twice?
Swift
func outer() -> () -> Void {
    var x = 0
    let inner = {
        x += 1
        print(x)
    }
    return inner
}

let closure = outer()
closure()
closure()
A1\n2
B0\n1
C1\n1
D2\n3
Attempts:
2 left
💡 Hint
Think about how the variable x is captured and modified by the closure.

Practice

(1/5)
1. What happens when a Swift closure captures a variable strongly by default?
easy
A. The closure keeps a strong reference, potentially causing memory leaks if not handled.
B. The variable is copied and changes inside the closure do not affect the original.
C. The closure does not keep any reference to the variable.
D. The variable is automatically released when the closure is created.

Solution

  1. Step 1: Understand default capture behavior

    By default, Swift closures capture variables strongly, meaning they keep a reference to the original variable.
  2. Step 2: Recognize memory implications

    If the closure and the captured variable reference each other, it can cause a retain cycle, leading to memory leaks.
  3. Final Answer:

    The closure keeps a strong reference, potentially causing memory leaks if not handled. -> Option A
  4. Quick Check:

    Strong capture = possible memory leak [OK]
Hint: Strong capture keeps variables alive, watch for retain cycles [OK]
Common Mistakes:
  • Thinking variables are copied by default
  • Assuming closures do not hold references
  • Believing variables auto-release on capture
2. Which syntax correctly declares a capture list to weakly capture a variable self in a Swift closure?
easy
A. { (weak self) in print(self) }
B. { self weak in print(self) }
C. { weak self -> Void in print(self) }
D. { [weak self] in print(self) }

Solution

  1. Step 1: Recall capture list syntax

    Capture lists are declared inside square brackets before the closure parameters, e.g., [weak self].
  2. Step 2: Match correct syntax

    { [weak self] in print(self) } uses the correct syntax: { [weak self] in ... }.
  3. Final Answer:

    { [weak self] in print(self) } -> Option D
  4. Quick Check:

    Capture list uses square brackets [weak self] [OK]
Hint: Capture lists use square brackets before closure parameters [OK]
Common Mistakes:
  • Using parentheses instead of square brackets
  • Placing 'weak' outside capture list
  • Incorrect arrow syntax in capture list
3. What will be printed by the following Swift code?
class Person {
    var name = "Alice"
    lazy var greet: () -> Void = { [unowned self] in
        print("Hello, \(self.name)!")
    }
}
let p = Person()
p.greet()
medium
A. Hello, !
B. Hello, Optional("Alice")!
C. Hello, Alice!
D. Runtime error due to unowned reference

Solution

  1. Step 1: Analyze closure capture

    The closure captures self as unowned, meaning it expects self to always exist when called.
  2. Step 2: Check code execution

    Instance p is created, greet closure is called, printing "Hello, Alice!" using self.name.
  3. Final Answer:

    Hello, Alice! -> Option C
  4. Quick Check:

    Unowned capture prints value safely if object exists [OK]
Hint: Unowned captures assume object exists, no optional needed [OK]
Common Mistakes:
  • Expecting Optional wrapping in output
  • Thinking unowned causes runtime error immediately
  • Assuming empty string prints
4. Identify the problem in this Swift code snippet and how to fix it:
class ViewController {
    var title = "Main"
    lazy var printTitle = {
        print(self.title)
    }
}
let vc = ViewController()
vc.printTitle()
medium
A. No problem, code runs fine and prints "Main".
B. Retain cycle due to strong self capture; fix with [weak self] capture list.
C. Syntax error: missing capture list brackets.
D. Runtime error: self is nil inside closure.

Solution

  1. Step 1: Identify capture type

    The closure captures self strongly by default, which can cause retain cycles if ViewController holds the closure.
  2. Step 2: Fix with weak capture

    Adding [weak self] in the capture list prevents retain cycle by capturing self weakly.
  3. Final Answer:

    Retain cycle due to strong self capture; fix with [weak self] capture list. -> Option B
  4. Quick Check:

    Strong capture in closures can cause retain cycles [OK]
Hint: Use [weak self] to avoid retain cycles in closures [OK]
Common Mistakes:
  • Ignoring retain cycles in lazy properties
  • Assuming no capture means no memory issues
  • Confusing syntax errors with memory issues
5. You have a Swift class with a closure property that captures a variable data. You want to ensure the closure does not keep data alive if the class instance is deallocated, but still access data safely inside the closure. Which capture strategy should you use?
hard
A. Capture data weakly and unwrap it safely inside the closure.
B. Capture data unowned without checks inside the closure.
C. Capture data strongly to keep it alive as long as the closure exists.
D. Do not capture data at all; pass it as a parameter instead.

Solution

  1. Step 1: Understand capture effects on memory

    Strong capture keeps data alive, which may cause memory leaks if the class is deallocated.
  2. Step 2: Choose safe capture method

    Weak capture allows data to be nil if deallocated; unwrapping safely avoids crashes.
  3. Step 3: Compare with unowned and no capture

    Unowned assumes data always exists, risking crashes. Not capturing requires passing data every time, which may be inconvenient.
  4. Final Answer:

    Capture data weakly and unwrap it safely inside the closure. -> Option A
  5. Quick Check:

    Weak capture + safe unwrap = safe memory handling [OK]
Hint: Use weak capture and optional unwrap for safe memory use [OK]
Common Mistakes:
  • Using unowned and risking runtime crashes
  • Strong capture causing retain cycles
  • Ignoring safe unwrapping of weak references
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard