Functions and Closures

Article · 2:00

Named functions with argument labels, and closures - the inline functions SwiftUI is built out of.

A Swift function declares the type of every parameter and of its return value. What makes it look different from other languages is argument labels: each parameter can have one name used by the caller and another used inside the body. This is why Swift reads the way it does - move(from: a, to: b) rather than move(a, b). Use _ as the external label when the call reads better without one.

A closure is a function without a name, written inline and passed as a value. They are everywhere in SwiftUI: the contents of a VStack, the action of a Button, the transform in a map are all closures. Swift provides several shorthands - omit the parameter list and use $0, omit the return on a single expression, move the final closure outside the parentheses - and the result is syntax that stops looking like a function call at all. That is deliberate, and Button("Save") { save() } is the pay-off.

The word "closure" means it closes over its surroundings: it captures the variables in scope where it was written, and keeps them alive. That is useful and it is also how you create a retain cycle, which is the subject of a later topic.

// Argument labels: "from" and "to" are for the caller, "start"/"end" inside.
func distance(from start: Double, to end: Double) -> Double {
    abs(end - start)          // single expression - return is implied
}
let d = distance(from: 3.0, to: 11.5)

// "_" removes the label when it reads better without.
func double(_ value: Int) -> Int { value * 2 }
let four = double(2)

// A default value makes a parameter optional at the call site.
func greet(_ name: String, politely: Bool = true) -> String {
    politely ? "Good evening, \(name)" : "Hi \(name)"
}

// Closures, from longest form to shortest.
let names = ["Ada", "Grace", "Alan"]
let a = names.sorted(by: { (l: String, r: String) -> Bool in return l < r })
let b = names.sorted(by: { l, r in l < r })
let c = names.sorted { $0 < $1 }      // trailing closure + shorthand

print(d, four, greet("Ada"), c)