0
0
Swiftprogramming~10 mins

Capture lists in closures in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Capture lists in closures
Define variable x = 10
Create closure with capture list [x
Closure captures current x value
Change x to 20
Call closure
Closure uses captured x (10), not current x (20)
End
This flow shows how a closure captures a variable's value at creation using a capture list, preserving it even if the variable changes later.
Execution Sample
Swift
var x = 10
let closure = { [x] in
  print(x)
}
x = 20
closure()
This code creates a closure that captures x's value at 10, then changes x to 20, but the closure prints the captured 10.
Execution Table
StepActionVariable xClosure CaptureOutput
1Initialize x10N/AN/A
2Create closure with capture list [x]10Captures x=10N/A
3Change x to 2020Captured x=10 (unchanged)N/A
4Call closure20Captured x=1010
5End20Captured x=10N/A
💡 Closure uses captured x=10, ignoring current x=20
Variable Tracker
VariableStartAfter Step 2After Step 3Final
x10102020
closure capture xN/A101010
Key Moments - 2 Insights
Why does the closure print 10 instead of 20 after x changes?
Because the closure captured x's value at creation (step 2), it keeps that value (10) even though x later changes to 20 (step 3). See execution_table rows 2 and 4.
What if we omit the capture list [x] in the closure?
Without a capture list, the closure captures x by reference, so it would print the current value of x (20) when called. This differs from the capture list behavior shown in step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what value does the closure capture at step 2?
A10
B20
CN/A
DClosure does not capture x
💡 Hint
Check the 'Closure Capture' column at step 2 in the execution_table.
At which step does variable x change to 20?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Variable x' column in execution_table to find when x changes.
If we remove the capture list [x], what will the closure print when called?
AError
B10
C20
DNothing
💡 Hint
Recall that without capture list, closure captures variable by reference, so it uses current x value at call time.
Concept Snapshot
Capture lists in closures:
- Syntax: { [var] in ... }
- Captures variable's value at closure creation
- Later changes to variable do not affect captured value
- Useful to fix variable state inside closure
- Without capture list, closure captures by reference
Full Transcript
This example shows how Swift closures can capture variables using capture lists. We start with variable x = 10. When we create a closure with [x], it captures the current value 10. Then we change x to 20. When we call the closure, it prints 10, the captured value, not 20. This behavior helps keep a fixed value inside the closure even if the original variable changes later. Without the capture list, the closure would print the current value of x when called.