SWIFT / CHAPTER 05

Closures and captured state

Advanced

Pass behavior and understand what a closure remembers.

By the end of this chapter

  • Read function types
  • Trace independent closure factories
  • Identify shared captured state

The idea

A closure is a value that can be passed to another function or stored for later use. Its parameter and return types describe the behavior a caller expects. A function accepting (Int) -> Bool can reuse one traversal with different selection rules. Short closure syntax is convenient, but named parameters often make a complex transformation easier to read and reason about.

Closures can capture values from the surrounding scope. A factory that declares a local counter and returns a closure creates independent retained state on each factory call. Two references to one returned closure share its state. Captures can also keep class instances alive, so delayed or stored callbacks need a deliberate ownership policy. Treat side effects as part of the closure’s contract instead of assuming every map or filter operation is pure.

Swift example
func makeCounter(_ start:Int)->()->Int {var n=start; return {n += 1; return n}}
let a=makeCounter(0)
let b=makeCounter(10)
print(a())
print(a())
print(b())
Result
1
2
11

Each factory call captures its own local variable, while repeated calls through a retain its updated state.

Try it yourself

Write a function that accepts a predicate and returns how many values satisfy it.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does a function of type (Int) -> Bool supply?