iOS ● ● ● Swift 6

Kodebits Day 5: Closure Capturing

Apr 13 2026
Values are captured by reference in closures by default in Swift.

What is the output?

var i = 0
var ops: [() -> ()] = []
for _ in 1...3 {
  ops.append { print(i) }
  i += 1
}
ops[0]()
ops[1]()
ops[2]()


Try it in the online Swift Playground →

[spoiler title="Solution"]

Answer:

3
3
3

Explanation:

Closures capture variables by reference. The loop finishes with i=3. All closures print the current value of i, which is 3.

[/spoiler]


Further Reading