Bird
Raised Fist0
Swiftprogramming~10 mins

Weak self and unowned self patterns in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Weak self and unowned self patterns
Start Closure Capture
↓
Capture self weakly or unowned
↓
Closure Executes
↓
Check if self exists (weak) or assume exists (unowned)
↓
Use self
↓
Closure Ends
This flow shows how closures capture self weakly or unowned, check self's existence, and safely use it or exit.
Execution Sample
Swift
class MyClass {
  var closure: (() -> Void)?
  var value = 10
  func setup() {
    closure = { [weak self] in
      print(self?.value ?? "No self")
    }
  }
}
This code sets up a closure capturing self weakly to avoid strong reference cycles.
Execution Table
StepActionself capturedself exists?OutputNotes
1Closure created with [weak self]weak reference to selfN/AN/AClosure holds weak self
2Closure called while self aliveweak reference to selfYes10self.value printed
3self deallocatedweak reference to selfNoNo selfself is nil, safe unwrap prints fallback
4Closure called after self deallocatedweak reference to selfNoNo selfNo crash, safe handling
5Closure created with [unowned self]unowned reference to selfN/AN/AClosure holds unowned self
6Closure called while self aliveunowned reference to selfYes10self.value printed
7self deallocatedunowned reference to selfNoCrashAccessing unowned self causes crash
8Closure called after self deallocatedunowned reference to selfNoCrashUnsafe access, program crashes
💡 Execution stops when closure finishes or program crashes due to unowned self access after deallocation
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 6After Step 7
self (weak)Strong referenceExistsNilN/AN/A
self (unowned)Strong referenceExistsN/AExistsDeallocated (dangling)
Key Moments - 3 Insights
Why does using [weak self] not crash when self is nil?
Because weak self is an optional reference. The closure checks if self exists before using it (see step 3 and 4 in execution_table), so it safely handles nil without crashing.
Why does using [unowned self] crash after self is deallocated?
Unowned self is a non-optional reference that assumes self always exists. If self is deallocated (step 7 and 8), accessing unowned self causes a runtime crash because it points to invalid memory.
When should I use weak self vs unowned self in closures?
Use weak self when self might be nil during closure execution and you want to avoid crashes (safe optional). Use unowned self only when you are sure self will outlive the closure, avoiding optional unwrapping.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is printed when the closure with [weak self] is called after self is deallocated?
A"No self"
B10
CCrash
Dnil
💡 Hint
Check step 4 in the execution_table where self is nil and output is "No self"
At which step does accessing unowned self cause a crash?
AStep 6
BStep 7
CStep 3
DStep 2
💡 Hint
Look at the execution_table rows describing unowned self usage and crash at step 7
If we change [weak self] to [unowned self] in the closure, what happens when self is deallocated before closure call?
AClosure prints "No self" safely
BClosure does not run
CProgram crashes due to invalid self access
DClosure runs but self is nil
💡 Hint
Refer to variable_tracker and execution_table steps 7 and 8 for unowned self crash behavior
Concept Snapshot
Weak self and unowned self are ways closures capture self to avoid strong reference cycles.
Weak self is optional and safe if self might be nil.
Unowned self is non-optional and assumes self always exists.
Use weak self when self can be deallocated before closure runs.
Use unowned self only when self outlives the closure.
Accessing unowned self after deallocation causes a crash.
Full Transcript
This visual trace shows how closures capture self in Swift using weak and unowned references. When a closure captures self weakly, it holds an optional reference that can become nil if self is deallocated. The closure safely checks if self exists before using it, preventing crashes. When self is alive, the closure prints self's value. After self is deallocated, the closure prints a fallback message "No self" safely. In contrast, capturing self as unowned means the closure assumes self always exists. If self is deallocated before the closure runs, accessing unowned self causes a runtime crash because it points to invalid memory. This trace highlights when to use weak self (safe optional) versus unowned self (non-optional but unsafe if self is gone). Understanding these patterns helps avoid memory leaks and crashes in Swift closures.

Practice

(1/5)
1. What is the main reason to use weak self inside a closure in Swift?
easy
A. To make self immutable inside the closure
B. To guarantee self will never be nil inside the closure
C. To prevent strong reference cycles and allow self to become nil
D. To create a copy of self for thread safety

Solution

  1. Step 1: Understand strong reference cycles

    Strong reference cycles happen when closures capture self strongly, causing memory leaks.
  2. Step 2: Role of weak self

    Using weak self makes the reference to self optional and allows it to become nil, breaking the cycle.
  3. Final Answer:

    To prevent strong reference cycles and allow self to become nil -> Option C
  4. Quick Check:

    Weak self avoids memory leaks = A [OK]
Hint: Weak self means self can be nil inside closures [OK]
Common Mistakes:
  • Thinking weak self guarantees non-nil self
  • Confusing weak with unowned self
  • Assuming weak self copies self
2. Which of the following is the correct syntax to capture self as unowned in a Swift closure?
easy
A. [weak self] in
B. [unowned self] in
C. [self unowned] in
D. [unowned] self in

Solution

  1. Step 1: Recall capture list syntax

    Swift uses square brackets with capture specifiers before in in closures.
  2. Step 2: Correct unowned syntax

    The correct syntax is [unowned self] in to capture self as unowned.
  3. Final Answer:

    [unowned self] in -> Option B
  4. Quick Check:

    Unowned capture syntax = [unowned self] in [OK]
Hint: Capture lists use square brackets with 'unowned self' [OK]
Common Mistakes:
  • Swapping order like [self unowned]
  • Missing brackets or 'in' keyword
  • Using weak instead of unowned when asked
3. Consider this Swift code snippet:
class Example {
    var closure: (() -> Void)?
    func setup() {
        closure = { [weak self] in
            print(self == nil ? "nil" : "not nil")
        }
    }
}
let example = Example()
example.setup()
example.closure?()
What will be printed when example.closure?() is called?
medium
A. not nil
B. Compilation error
C. nil
D. Runtime crash

Solution

  1. Step 1: Analyze weak self capture

    The closure captures self weakly, so inside the closure self is optional.
  2. Step 2: Check self lifetime

    The example instance is still alive when closure?() is called, so self is not nil.
  3. Final Answer:

    not nil -> Option A
  4. Quick Check:

    Weak self is alive here = not nil [OK]
Hint: If instance exists, weak self is not nil inside closure [OK]
Common Mistakes:
  • Assuming weak self is always nil
  • Confusing weak self with unowned self
  • Expecting runtime crash due to optional
4. Identify the problem in this Swift code and choose the best fix:
class Person {
    var name = "Alice"
    lazy var greet: () -> Void = {
        print("Hello, \(self.name)!")
    }
}
let p = Person()
p.greet()
medium
A. Make greet a regular function instead of closure
B. Use [weak self] in closure to avoid strong reference cycle
C. Use [unowned self] in closure to avoid strong reference cycle
D. No problem; code works fine

Solution

  1. Step 1: Detect strong reference cycle risk

    The closure captures self strongly, and greet is lazy var, so cycle possible.
  2. Step 2: Choose unowned self for non-optional self

    Since self will always exist when greet is called, unowned self is safe and avoids optional unwrapping.
  3. Final Answer:

    Use [unowned self] in closure to avoid strong reference cycle -> Option A
  4. Quick Check:

    Unowned self for guaranteed self = C [OK]
Hint: Use unowned self if self always exists in closure [OK]
Common Mistakes:
  • Ignoring strong reference cycles
  • Using weak self and forcing unwrap unnecessarily
  • Thinking no problem exists
5. You have a Swift class that manages a network request with a closure callback. You want to avoid memory leaks but also avoid optional unwrapping inside the closure. Which pattern should you use and why? Choose the best explanation.
hard
A. Do not capture self at all to avoid any reference issues
B. Use weak self to avoid leaks and unwrap self safely inside closure
C. Use strong self to keep the instance alive during the closure execution
D. Use unowned self because self will outlive the closure, avoiding optionals

Solution

  1. Step 1: Understand lifetime of self and closure

    If self will definitely exist while closure runs, unowned self is safe and avoids optionals.
  2. Step 2: Compare weak vs unowned for this case

    weak self requires optional unwrapping, but unowned self assumes self exists, simplifying code and avoiding leaks.
  3. Final Answer:

    Use unowned self because self will outlive the closure, avoiding optionals -> Option D
  4. Quick Check:

    Unowned self for guaranteed lifetime = A [OK]
Hint: Use unowned if self guaranteed alive, else weak [OK]
Common Mistakes:
  • Using weak self but not unwrapping safely
  • Using strong self causing memory leaks
  • Ignoring self capture causing leaks
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