Consider this Swift code where a closure captures a variable from its context. What will be printed?
var count = 0 let incrementer = { count += 1; print(count) } incrementer() incrementer() print(count)
Closures capture variables by reference, so changes inside affect the original variable.
The closure increments count each time it is called, so the first call prints 1, the second prints 2, and the final print shows the updated count value 2.
Look at this Swift code where a closure captures a constant. What will be printed?
let number = 5 let printNumber = { print(number) } printNumber()
Constants can be captured by closures and used inside them.
The closure captures the constant number and prints its value 5.
Examine this Swift code where a closure captures a loop variable. Why does it print the same number multiple times?
var closures: [() -> Void] = [] for i in 1...3 { closures.append { print(i) } } closures.forEach { $0() }
Think about how Swift captures loop variables in closures.
Swift captures i by reference in the loop, so all closures share the same i which ends at 4 after the loop, so all print 4.
What will this Swift code print? It uses a capture list to capture a variable by value.
var value = 10 let closure = { [value] in print(value) } value = 20 closure()
Capture lists let you capture a variable's value at the time the closure is created.
The closure captures value as 10 when created, so it prints 10 even though value changed later.
Choose the correct statement about how Swift closures capture values from their context.
Think about how capture lists affect variable capturing.
By default, Swift closures capture variables by reference, but you can use capture lists to capture by value.