Bird
Raised Fist0
Swiftprogramming~10 mins

Capturing values from context in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Capturing values from context
Define variable x = 10
↓
Define closure capturing x
↓
Call closure
↓
Closure uses captured x
↓
Print result
↓
Change x after closure defined
↓
Call closure again
↓
Closure uses current value of captured x
This flow shows how a closure captures a variable by reference from its surrounding context and uses the current value of the captured variable when called, even after the original variable changes later.
Execution Sample
Swift
var x = 10
let closure = { print("x is \(x)") }
closure()
x = 20
closure()
This code defines a variable x, a closure capturing x, calls the closure, changes x, then calls the closure again to show captured value behavior.
Execution Table
StepActionVariable xClosure Output
1Define x = 1010
2Define closure capturing x10
3Call closure first time10x is 10
4Change x to 2020
5Call closure second time20x is 20
💡 Program ends after second closure call showing updated x value
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 5
x10102020
Key Moments - 2 Insights
Does the closure keep the original value of x or the updated value after x changes?
In Swift, closures capture variables by reference, so they see the updated value of x when called, as shown in steps 3 and 5 of the execution_table.
Why does the closure print "x is 20" after x changes to 20?
Because the closure captures the variable x itself, not just its value at definition, so it reflects the current value of x when called (see step 5 in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is printed when the closure is called the first time?
A"x is 0"
B"x is 10"
C"x is 20"
DNo output
💡 Hint
Check step 3 in the execution_table where the closure is called first time.
At which step does the variable x change its value?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Look at the variable_tracker and execution_table rows for when x changes.
If x was a constant (let x = 10), what would happen when trying to change x at step 4?
AThe program would compile and run normally
BThe closure would capture the value 10 and never change
CThere would be a compile-time error at step 4
DThe closure would print "x is 20" anyway
💡 Hint
In Swift, constants cannot be changed after definition; check step 4 where x is assigned 20.
Concept Snapshot
Capturing values from context in Swift:
- Closures capture variables by reference.
- They use the current value of captured variables when called.
- Changing a variable after closure definition affects closure output.
- Constants (let) cannot be changed after definition.
- Useful for delayed execution with access to surrounding variables.
Full Transcript
This example shows how Swift closures capture variables from their surrounding context. We start by defining a variable x with value 10. Then we define a closure that prints x. When we call the closure the first time, it prints "x is 10". After that, we change x to 20. Calling the closure again prints "x is 20" because closures capture variables by reference, not by value. This means the closure sees the current value of x when it runs. If x were a constant, changing it would cause a compile error. This behavior helps closures access and use variables from their context even after that context changes.

Practice

(1/5)
1. What does it mean when a Swift closure captures values from context?
easy
A. The closure only works with global variables
B. The closure creates new variables unrelated to the surrounding scope
C. The closure cannot access any variables outside its own body
D. The closure keeps a reference to variables from its surrounding scope

Solution

  1. Step 1: Understand closure context

    A closure can access variables defined outside its own body, in the surrounding scope.
  2. Step 2: Capturing means referencing

    Capturing means the closure keeps a reference to those external variables so it can use them later.
  3. Final Answer:

    The closure keeps a reference to variables from its surrounding scope -> Option D
  4. Quick Check:

    Closure captures = keeps reference [OK]
Hint: Closures remember variables around them by reference [OK]
Common Mistakes:
  • Thinking closures create new independent variables
  • Believing closures cannot access outside variables
  • Confusing capture with copying values
2. Which of the following is the correct syntax to capture a value by copy in a Swift closure?
easy
A. let closure = { [value] in print(value) }
B. let closure = { [value = value] in print(value) }
C. let closure = { value in print(value) }
D. let closure = { capture value in print(value) }

Solution

  1. Step 1: Recognize capture list syntax

    To capture by value, Swift uses a capture list with syntax like [var = value].
  2. Step 2: Match correct syntax

    let closure = { [value = value] in print(value) } uses [value = value] which copies the current value into the closure.
  3. Final Answer:

    let closure = { [value = value] in print(value) } -> Option B
  4. Quick Check:

    Capture by copy uses [var = var] syntax [OK]
Hint: Use capture list with assignment to copy value [OK]
Common Mistakes:
  • Omitting capture list brackets
  • Using capture list without assignment
  • Writing invalid keywords like 'capture'
3. What will be printed by this Swift code?
var x = 10
let closure = { print(x) }
x = 20
closure()
medium
A. 20
B. nil
C. Compilation error
D. 10

Solution

  1. Step 1: Understand reference capture

    The closure captures x by reference, so it uses the current value when called.
  2. Step 2: Check value at call time

    Since x was changed to 20 before calling the closure, it prints 20.
  3. Final Answer:

    20 -> Option A
  4. Quick Check:

    Reference capture prints updated value [OK]
Hint: Closures print current variable value unless captured by copy [OK]
Common Mistakes:
  • Assuming closure prints original value 10
  • Expecting compilation error due to variable change
  • Thinking closure prints nil
4. Identify the error in this Swift closure code:
var count = 0
let increment = { count += 1 }
increment()
print(count)
medium
A. No error; code runs and prints 1
B. Closure must declare 'count' as inout parameter
C. Cannot modify 'count' inside closure without 'self.'
D. Closure cannot capture variables declared outside

Solution

  1. Step 1: Check variable mutability

    count is a variable (var), so it can be modified inside the closure.
  2. Step 2: Verify closure behavior

    The closure increments count by 1, then printing count outputs 1.
  3. Final Answer:

    No error; code runs and prints 1 -> Option A
  4. Quick Check:

    Mutable var can be changed inside closure [OK]
Hint: Vars can be changed inside closures without extra syntax [OK]
Common Mistakes:
  • Thinking 'self.' is required outside classes
  • Believing inout needed for closure variables
  • Assuming closures cannot modify external vars
5. You want a Swift closure to capture the value of a variable at the moment the closure is created, so later changes to the variable don't affect the closure. How do you do this?
hard
A. Declare the variable as a constant (let) before the closure
B. Use a global variable instead of a local one
C. Use a capture list to copy the variable value inside the closure
D. Modify the variable inside the closure before using it

Solution

  1. Step 1: Understand default capture behavior

    By default, closures capture variables by reference, so changes affect the closure.
  2. Step 2: Use capture list to copy value

    Using a capture list like [value = variable] copies the current value into the closure, isolating it from later changes.
  3. Final Answer:

    Use a capture list to copy the variable value inside the closure -> Option C
  4. Quick Check:

    Capture list copies value to freeze it [OK]
Hint: Capture list copies value to freeze it at closure creation [OK]
Common Mistakes:
  • Thinking 'let' alone freezes variable for closure
  • Using global variables to avoid capture issues
  • Modifying variable inside closure doesn't freeze value
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