The Analogy: The Portable Shop Jig
A metal shop keeps two kinds of tools for shaping parts, and the difference between them is exactly the difference between a function and a closure. The first is the big arbor press bolted to the workbench. It never moves. Above it sit three labeled input chutes -- one marked STOCK, one marked FROM, one marked TO -- and below it a single output tray. Any worker who wants a part bent walks up, drops the raw stock in the STOCK chute, sets the two dials, pulls the handle, and collects the finished piece from the tray. The press has a name stenciled on its side, it lives in one place, and everyone uses the same one. That is a named function: declared once, called from anywhere, addressed by its label.
The second tool is the portable jig. A worker assembles it on a clipboard-sized plate -- a couple of guide pins, a stop block, a template -- and it has no nameplate at all. You can carry it to any station, hand it to a coworker mid-shift, or clamp it inside a larger machine as a drop-in insert so the big machine now does the jig's little job as part of its cycle. The press's labeled chutes are its argument labels, the way an outsider addresses it; the internal cam names stamped inside are its parameter names, shorthand the mechanism uses privately. A pre-loaded chute that already holds a default rivet is a default parameter, and a wide hopper that will swallow any number of rivets at once is a variadic parameter.
The interesting part is what the jig holds onto. When a worker assembles a jig at bench four, they often clamp it directly onto live instruments already there -- the bench's dial gauge and the supervisor's running tally sheet. The jig does not photocopy the numbers it sees at assembly time; it grips the actual gauge and the actual sheet, so whenever it later runs it reads whatever those instruments now say. That live grip is a capture. If the jig is dropped into the "run on the next shift" drawer and still reaches back to bench four's gauge when it finally fires, that is an escaping closure. And if the worker deliberately copies the gauge's current reading onto the jig's own plate instead of gripping the gauge, that written-down snapshot is a capture list.
Here is where it goes wrong. One afternoon a jig is assembled gripping "today's work-order clipboard" -- a live reference to the reusable board hanging at the station. The jig is filed away in the next-shift drawer. A week later that same board has been wiped and reissued to a completely different customer with different tolerances. The filed jig fires, faithfully reads the board it was told to hold, and stamps every part to the wrong spec. The jig did nothing wrong; it read exactly what it had captured. The lesson is blunt: a captured reference is only as stable as the thing it grabbed, and gripping something that will be reused later is how a perfectly correct closure produces confidently wrong results.
Syntax or Core Structure
Swift functions and closures share one type system: a closure is simply a function without a name, and both can be stored in variables, passed as arguments, and returned. The pieces below are the vocabulary the rest of this lesson builds on.
// A named function: argument labels (from/to) differ from parameter names (start/end)
func distance(from start: Int, to end: Int) -> Int {
return end - start
}
distance(from: 3, to: 10) // 7
// "_" drops the label; a default value makes an argument optional at the call site
func greet(_ name: String, punctuation: String = "!") -> String {
return "Hi " + name + punctuation
}
greet("Ada") // "Hi Ada!"
// A variadic parameter accepts zero or more values
func total(_ numbers: Int...) -> Int { numbers.reduce(0, +) }
total(1, 2, 3, 4) // 10
// The same logic as a closure stored in a constant
let add: (Int, Int) -> Int = { a, b in a + b }
add(2, 5) // 7
// A trailing closure moves the final closure argument outside the parentheses
let squares = [1, 2, 3].map { $0 * $0 } // [1, 4, 9]
Technical Depth: How Functions and Closures Behave
Functions are first-class values
A function has a type -- (Int) -> Int -- in the same way that Int or String is a type. That means you can store a function in a constant, pass it into another function, and return it. A function that accepts or returns another function is called a higher-order function.
| Written form | Meaning |
|---|---|
() -> Void | takes nothing, returns nothing |
(Int) -> Int | takes one Int, returns an Int |
(Int, Int) -> Bool | takes two Ints, returns a Bool |
([Int]) -> Int | takes an array of Int, returns an Int |
func triple(_ x: Int) -> Int { x * 3 }
func apply(_ f: (Int) -> Int, to value: Int) -> Int { f(value) }
let op: (Int) -> Int = triple // store a function in a constant
print(op(5)) // 15
print(apply(triple, to: 4)) // 12
let nums = [3, 5, 8]
print(nums.map(triple).reduce(0, +)) // 9 + 15 + 24 = 48
Output:
15
12
48
Closures capture by reference, not by copy
A closure does not copy the variables it uses; it captures the storage itself. The counter below returns a closure that keeps incrementing the same count variable long after makeCounter has returned, while a second counter gets its own independent count.
func makeCounter() -> () -> Int {
var count = 0
return {
count += 1
return count
}
}
let next = makeCounter()
print(next()) // 1
print(next()) // 2
print(next()) // 3
let other = makeCounter() // a fresh, separate count
print(other()) // 1
print(next()) // 4
Output:
1
2
3
1
4
Trailing closures, shorthand, and higher-order pipelines
Because the last closure argument can move outside the parentheses, chains of map, filter, and reduce read top to bottom. The forms below all describe the same closure with progressively less ceremony.
| Form | Example |
|---|---|
| Full | { (n: Int) -> Int in return n * n } |
| Inferred types | { n in n * n } |
| Shorthand arguments | { $0 * $0 } |
| Trailing closure | nums.map { $0 * $0 } |
| Operator function | nums.reduce(0, +) |
let values = [5, 2, 8, 1, 9, 3]
let oddSquareSum = values
.filter { $0 % 2 == 1 } // [5, 1, 9, 3]
.map { $0 * $0 } // [25, 1, 81, 9]
.reduce(0, +) // 116
print(oddSquareSum) // 116
let names = ["ada", "grace", "alan"]
let titled = names.map { $0.capitalized }.sorted()
print(titled) // ["Ada", "Alan", "Grace"]
Output:
116
["Ada", "Alan", "Grace"]
Capture lists freeze a snapshot
Sometimes you want the opposite of live capture: the value as it stood when the closure was created. A capture list, written in square brackets at the start of the closure, copies the named value in right then. Here byValue captures multiplier as 2, while byReference keeps reading the live variable.
var multiplier = 2
let byValue = { [multiplier] (x: Int) -> Int in x * multiplier }
let byReference = { (x: Int) -> Int in x * multiplier }
multiplier = 10
print(byValue(5)) // 10 -- captured 2 at creation
print(byReference(5)) // 50 -- reads the current 10
Output:
10
50
Real World Example: A Discount Rule Pipeline
A checkout needs to apply a list of price adjustments -- a percentage off, a flat coupon, a final rounding step -- to a cart subtotal. Modeling each adjustment as a PriceRule (a closure of type (Double) -> Double) lets the checkout store them in an array and fold them together, so adding or removing a promotion is a one-line change.
struct LineItem {
let name: String
let unitPrice: Double
let quantity: Int
}
typealias PriceRule = (Double) -> Double
func percentOff(_ rate: Double) -> PriceRule {
return { subtotal in subtotal * (1.0 - rate) }
}
func flatOff(_ amount: Double) -> PriceRule {
return { subtotal in max(0.0, subtotal - amount) }
}
func makeRounder(_ places: Int) -> PriceRule {
let factor = pow(10.0, Double(places))
return { value in (value * factor).rounded() / factor }
}
func subtotal(of cart: [LineItem]) -> Double {
return cart.map { $0.unitPrice * Double($0.quantity) }.reduce(0.0, +)
}
func apply(_ rules: [PriceRule], to amount: Double) -> Double {
return rules.reduce(amount) { running, rule in rule(running) }
}
let cart = [
LineItem(name: "Notebook", unitPrice: 4.50, quantity: 3),
LineItem(name: "Gel Pen", unitPrice: 1.25, quantity: 4),
LineItem(name: "Marker", unitPrice: 2.00, quantity: 2)
]
for item in cart {
let line = item.unitPrice * Double(item.quantity)
print("\(item.name): \(item.quantity) x \(item.unitPrice) = \(line)")
}
let base = subtotal(of: cart)
print("subtotal: \(base)")
let rules: [PriceRule] = [percentOff(0.10), flatOff(2.0), makeRounder(2)]
let finalPrice = apply(rules, to: base)
print("after rules: \(finalPrice)")
Output:
Notebook: 3 x 4.5 = 13.5
Gel Pen: 4 x 1.25 = 5.0
Marker: 2 x 2.0 = 4.0
subtotal: 22.5
after rules: 18.25
The program builds three rules with factory functions. percentOff, flatOff, and makeRounder each return a closure that has captured its configuration -- the rate, the coupon amount, the rounding factor -- so the returned PriceRule carries that setting with it wherever it goes. This is the portable jig from the analogy: a small self-contained tool that remembers how it was set up.
subtotal(of:) maps each line item to its extended price and reduces the results with the + operator function, giving 13.5 + 5.0 + 4.0 = 22.5. The apply function then folds the rule array over that subtotal with reduce, feeding each rule's output into the next: 22.5 becomes 20.25 after ten percent off, 18.25 after the flat two-dollar coupon, and stays 18.25 once rounded to two places.
Because every rule shares the type (Double) -> Double, the pipeline is fully composable. A new promotion is added by writing one more factory and dropping its result into the rules array; nothing else changes. The checkout never needs to know what any individual rule does -- it only knows how to feed one rule's result into the next.
The design flaw is that rule order is implicit and unchecked. makeRounder(2) only produces a clean receipt because it happens to sit last in the array. If a maintainer appends another percentOff after it, or simply reorders the list, the printed total silently grows trailing digits like 18.225 and no compiler error or type mismatch flags it, because a rounding step and a discount step have the identical (Double) -> Double signature. The fix is to tag each rule with a phase -- discount versus formatting -- and sort or validate the pipeline before applying, so the rounding step is guaranteed to run last no matter what order the rules were added in.
Common Mistakes
- Expecting a snapshot when the closure captured a reference: A closure holds the variable itself, not its value at creation, so a value changed after the closure was made is the value the closure sees when it finally runs.
- Creating a retain cycle with
selfin an escaping closure: Capturingselfstrongly inside a stored closure keeps the object alive indefinitely; use[weak self]when the closure outlives the current scope. - Confusing the argument label with the parameter name: The outward label (how callers write the call) and the internal name (how the body uses it) are independent, and you do not have to make them match.
- Forgetting that a returned closure keeps its captured variables alive: The local
vara factory closes over lives as long as the returned closure does, which is the point but also a memory surprise. - Getting
@escapingwrong: Marking a closure escaping when it does not (or omitting it when it does) changes the contract; the compiler either complains or you leak memory. - Cramming multiple statements behind
$0shorthand: Shorthand names read well for one expression, but for multi-line bodies you should name the parameters so the code stays legible. - Mutating the same captured
varfrom two closures and being surprised they share it: Both closures point at one storage location, so one closure's write is immediately visible to the other. - Assuming dictionary or set iteration order inside a closure is stable: Higher-order operations over unordered collections yield an unspecified order; sort first if the output must be deterministic.
- Relying on the implicit order of same-typed rules in a pipeline: When every step is
(Double) -> Double, nothing enforces that formatting runs after arithmetic, so order becomes a silent correctness bug.
Best Practices
- Write argument labels that read like a sentence:
move(from:to:)at the call site documents itself far better thanmove(_:_:). - Use
[weak self]in escaping closures that outlive their scope: It breaks the retain cycle and makes the ownership relationship explicit. - Prefer
map,filter, andreduceover manual loops when they clarify intent: A pipeline states what you want; a loop states how to get it. - Keep closures short and extract to a named function when logic grows: A closure longer than a few lines is usually a function that wants a name.
- Use a capture list to snapshot a value you do not want mutated later:
[x]freezesxat creation, protecting the closure from outside changes. - Give parameters default values instead of writing overloaded wrappers: One function with defaults is easier to maintain than five near-identical ones.
- Annotate
@escapingdeliberately and document the closure's lifetime: Readers need to know whether a callback runs now or later. - Name a recurring closure type with a
typealias:typealias PriceRule = (Double) -> Doublemakes signatures readable and intent obvious.
Practice Exercises
- Make a multiplier factory: Write
makeMultiplier(factor: Int) -> (Int) -> Intthat returns a closure multiplying its input byfactor, then show that two multipliers built with different factors are fully independent. - Build a transform pipeline: Given an
[Int], chainfilter,map, andreduceto sum the squares of the even numbers, and note each intermediate array in a trailing comment. - Demonstrate capture semantics: Create two closures over the same
var, one using a capture list and one not, mutate the variable afterward, then explain why the two results differ. - Fix the discount pipeline flaw: Tag each
PriceRulewith a phase (discount or formatting) and rewriteapplyso the rounding rule always runs last regardless of the order rules were added.