Calls that read like sentences
Compare two ways of calling the same function:
move(3, 4, true)
move(from: 3, to: 4, animated: true)The first could mean anything. The second needs no comment. Swift was designed around the second style: almost every parameter has an argument label that appears at the call site, and the official API Design Guidelines ask you to choose names so that each call forms a grammatical English phrase. This is Swift's inheritance from Objective-C, where method names were famously long and descriptive, but tamed: labels are short, and you can omit one when the function name already says what the argument is (print(x), max(a, b)).
The second half of this lesson is about closures: functions without names that you write right where you use them. Swift code is full of them, because the standard library is designed around passing behaviour into functions: sorted { $0.price < $1.price }, filter { $0.isActive }, and in apps, "run this when the button is tapped" or "run this when the download finishes". Understanding how closures capture variables, and when they outlive the call that received them, is essential for the memory and concurrency lessons later.
Declaring functions
A function declaration lists, for each parameter, an optional argument label, a parameter name and a type, then the return type after ->:
func distance(from start: Double, to end: Double) -> Double {
return abs(end - start)
}
distance(from: 2, to: 9.5) // 7.5- If you write one name, it serves as both label and parameter name:
func area(width: Double, height: Double)is called asarea(width: 3, height: 4). - Write
_as the label to omit it at the call site:func square(_ x: Int)is called assquare(5). - A body that is a single expression returns it without
return. - A function with no
->returnsVoid, the empty tuple(). - Parameters are constants. Assigning to one fails with
left side of mutating operator isn't mutable: 'x' is a 'let' constant. Copy it into a localvarif you need to change it, or useinout(below).
Labels are part of a function's name. distance(from:to:) and distance(between:and:) are two different functions and can coexist, which is how the standard library offers index(after:) and index(before:) side by side. When people write about Swift functions, they name them with their labels, like that.
func greet(_ name: String, from city: String = "Accra", times: Int = 1) -> String {
let hello = Array(repeating: "Hello", count: times).joined(separator: ", ")
return "\(hello), \(name) from \(city)!"
}
print(greet("Yaw"))
print(greet("Lucía", from: "Bogotá"))
print(greet("Ivan", times: 2))
func average(of values: Double...) -> Double? {
guard !values.isEmpty else { return nil }
return values.reduce(0, +) / Double(values.count)
}
print(average(of: 3, 4, 8) ?? 0, average() ?? 0)
func bounds(of numbers: [Int]) -> (low: Int, high: Int)? {
guard var low = numbers.first else { return nil }
var high = low
for n in numbers.dropFirst() {
low = min(low, n)
high = max(high, n)
}
return (low, high)
}
if let b = bounds(of: [8, -2, 15, 4]) {
print("from \(b.low) to \(b.high)")
}
func moveFirstToEnd(_ queue: inout [String]) {
guard !queue.isEmpty else { return }
queue.append(queue.removeFirst())
}
var queue = ["Ama", "Bo", "Cyrus"]
moveFirstToEnd(&queue)
print(queue)Hello, Yaw from Accra!
Hello, Lucía from Bogotá!
Hello, Hello, Ivan from Accra!
5.0 0.0
from -2 to 15
["Bo", "Cyrus", "Ama"]Four features appear here:
- Default values (
city: String = "Accra") let callers leave arguments out. Put parameters with defaults after those without, and you can skip any of them, as the third call skipsfrom:. Default values replace most of the overloads you might write in Java. - A variadic parameter (
Double...) accepts any number of arguments, including none, and arrives in the function as an array. - A tuple return with named elements hands back two values at once. Wrapped in an optional, it can also say "there is no answer", here for an empty list.
- An
inoutparameter can be changed by the function, and the change is visible to the caller when the function returns. The caller must write&before the argument, so that anyone reading the call can see that it may be modified. Useinoutsparingly; returning a new value is usually clearer. It exists for cases likeswap(&a, &b)and for efficiency with large values.
Functions are values
Every function has a type made of its parameter types and its return type. square(_:) above has type (Int) -> Int; distance(from:to:) has type (Double, Double) -> Double (labels are not part of the type). You can store a function in a constant, put functions in an array, pass one to another function, and return one from a function:
func double(_ x: Int) -> Int { x * 2 }
func negate(_ x: Int) -> Int { -x }
let steps: [(Int) -> Int] = [double, negate, double]
var value = 5
for step in steps {
value = step(value)
}
// value is now -20Functions that take or return functions are called higher-order functions, and they are everyday tools, not exotic ones. You have already used two: compactMap and reduce take a function telling them what to do with each element. Even operators are functions: reduce(0, +) passes the + function for integers, and sorted(by: >) passes >.
Functions can also be nested: declared inside another function, visible only there, and able to use the outer function's parameters and local variables. Nesting is a tidy way to give a helper a name without adding it to the whole program; you will see one in the capturing example below. Functions may call themselves recursively, nested or not, and Swift does not limit recursion depth beyond the size of the thread's stack, so very deep recursion (hundreds of thousands of levels) can crash where a loop would not. Swift does not promise tail-call elimination either, so a recursive function written in tail position is no safer in this respect than any other. For deep or unbounded repetition, write a loop.
Closures, from long to short
Definition— closure
A closure is a self-contained block of code that can be passed around and called later. Closure expressions are written in braces: { (parameters) -> ReturnType in statements }. Named functions are closures too, of a special kind.
Swift lets you shorten a closure expression in steps whenever the compiler can infer what you left out: the parameter and return types (from context), the return (for a single expression), the parameter names (use $0, $1, ...), and even the parentheses of the call, when the closure is the last argument (trailing closure syntax).
let marks = [
("Zainab", 78), ("Kenji", 91), ("Olga", 64),
("Tariq", 91), ("Inés", 55), ("Mateo", 83),
]
// Closures: full form, then shorter and shorter.
let passed = marks.filter({ (entry: (String, Int)) -> Bool in
return entry.1 >= 60
})
let names = passed.map { entry in entry.0 }
let total = passed.reduce(0) { $0 + $1.1 }
print(names)
print("Average of those who passed: \(total / passed.count)")
// Highest mark first; ties broken alphabetically.
let ranking = marks.sorted { a, b in
a.1 != b.1 ? a.1 > b.1 : a.0 < b.0
}
for (place, entry) in ranking.prefix(3).enumerated() {
print(place + 1, entry.0, entry.1)
}
// Group names by band with reduce(into:).
let bands = marks.reduce(into: [String: [String]]()) { result, entry in
let band = entry.1 >= 85 ? "A" : entry.1 >= 70 ? "B" : "C"
result[band, default: []].append(entry.0)
}
for band in bands.keys.sorted() {
print(band, bands[band] ?? [])
}
print(marks.contains { $0.1 == 100 }, marks.allSatisfy { $0.1 > 50 })
print([5, 3, 9].sorted(by: >), [3, 1, 2].map(String.init).joined(separator: "-"))["Zainab", "Kenji", "Olga", "Tariq", "Mateo"]
Average of those who passed: 81
1 Kenji 91
2 Tariq 91
3 Mateo 83
A ["Kenji", "Tariq"]
B ["Zainab", "Mateo"]
C ["Olga", "Inés"]
false true
[9, 5, 3] 3-1-2Walk through the forms. The filter call spells out everything: parameter type, return type, return. The map call drops the types and return and names its parameter entry. The reduce call goes all the way to $0 (the running total) and $1 (the next element), and passes the closure after the parentheses. When the closure is the only argument, the parentheses disappear entirely, as in marks.sorted { ... }.
Which form is best? Experienced developers use $0 for very short closures where the meaning is obvious ({ $0.1 >= 60 }) and real names as soon as there are two parameters or more than one line, as in the sorted call, where a and b make the tie-breaking rule readable. reduce(into:) is the efficient way to build a dictionary or array from a sequence: the closure receives the result as an inout parameter and mutates it in place instead of copying it on every step. Finally, map(String.init) passes an initializer as a function: closures and named functions are interchangeable.
A note on sorted: when ties matter, say how to break them, as ranking does. Then the order of the result depends only on the data, not on the order in which the elements happened to arrive, and a reader can see the rule.
Several closures at once
Some functions take more than one closure: one for success and one for failure, or, in SwiftUI, one for a button's action and one for its label. Since Swift 5.3 (SE-0279) you can write all of them as multiple trailing closures: the first follows the call's parentheses without a label, and each further one follows the closing brace with its label.
let scores = ["Abebe": 42, "Sione": 37]
func lookUpScore(
for player: String,
onSuccess: (Int) -> Void,
onFailure: (String) -> Void
) {
if let score = scores[player] {
onSuccess(score)
} else {
onFailure("no player called \(player)")
}
}
for name in ["Abebe", "Hana"] {
lookUpScore(for: name) { score in
print("\(name) scored \(score)")
} onFailure: { reason in
print("Lookup failed: \(reason)")
}
}Abebe scored 42
Lookup failed: no player called HanaBoth closures are non-escaping (they are called before lookUpScore returns), and both capture name from the loop. A long parameter list is broken over several lines with the closing parenthesis on its own line, the layout swift format produces. This "success or failure callback" style was how asynchronous Swift was written for years; since Swift 5.5, async functions and errors (later in the course) usually replace it with straight-line code. You will still meet it in older codebases and in APIs that report several events over time.
Capturing, escaping and sharing
A closure can use variables from the scope where it was written, and it keeps them alive for as long as it exists. This is called capturing, and it is what makes closures more than plain functions.
// A function that returns a function. The closure captures `count`.
func makeCounter(step: Int) -> () -> Int {
var count = 0
return {
count += step
return count
}
}
let byOne = makeCounter(step: 1)
let byTen = makeCounter(step: 10)
print(byOne(), byOne(), byOne())
print(byTen(), byTen())
// Closures are reference types: two names, one shared captured variable.
let alias = byOne
print(alias(), byOne())
// An escaping closure is stored and called later.
func demoEscaping() {
var pending: [() -> Void] = []
func later(_ work: @escaping () -> Void) {
pending.append(work)
}
var message = "first"
later { print("capturing the variable:", message) }
later { [message] in print("capturing a copy:", message) }
message = "second"
for job in pending {
job()
}
}
demoEscaping()1 2 3
10 20
4 5
capturing the variable: second
capturing a copy: firstEach call to makeCounter creates a fresh count variable, and the returned closure keeps it alive after makeCounter has returned. byOne and byTen therefore count independently. But alias is not a new counter: closures are reference types, so alias and byOne are two names for the same closure and the same captured count, which goes on to 4 and 5.
The last part shows two important ideas.
Escaping. By default a closure parameter is non-escaping: Swift assumes it will only be called during the function call, which lets the compiler optimize it and lets you use it without worrying about lifetimes. A closure that will be stored and called later, after the function returns, must be marked @escaping. Remove the annotation from later and the compiler refuses to put work in the array (converting non-escaping parameter 'work' to generic parameter 'Element' may allow it to escape). In real code, escaping closures are completion handlers, event callbacks and stored configuration, and the annotation is a warning sign to the reader: this closure lives on, so think about what it captures.
Capture lists. A plain capture captures the variable, so the first stored closure sees the value at the time it runs: second. A capture list, [message] in, copies the value when the closure is created, so the second closure prints first. Capture lists matter most when a closure captures an object: in the memory lesson you will write [weak self] to keep a closure from keeping an object alive forever.
Note
The nested function later lives inside demoEscaping so that pending is a local variable. Top-level variables in main.swift belong to the main actor in Swift 6, and a plain global function is not allowed to change them; you will see why in the concurrency lesson.
Naming like a Swift programmer
The API Design Guidelines shape how Swift code reads, and following them is the fastest way to make your code look professional. A few rules carry most of the weight:
- Clarity at the point of use matters most. Write the call first, then design the declaration so that the call reads well:
names.remove(at: 2),view.insert(button, at: 0). - Omit needless words.
removeElement(element)repeats the type;remove(element)is enough. - Name by side effects. A method that changes its receiver is a verb in the imperative (
sort(),append(_:)); its non-mutating partner is a noun phrase or a past participle (sorted(),appending(_:)). Swift's standard library uses this pairing everywhere, soarray.sort()sorts in place andarray.sorted()returns a new array. - Boolean properties read as assertions:
isEmpty,hasPrefix(_:),canUndo.
Common misconceptions
Misconception
"$0 makes code shorter, so it is always better." Shorthand arguments are great in one-liners. In a closure of several lines, or with several parameters, $0 and $1 force the reader to remember what each one is. Give them names.
Misconception
"inout passes a reference, like a pointer." Semantically, inout copies the value in, lets the function change its copy, and copies it back out when the function returns (the compiler usually optimizes this into a direct reference). You cannot keep an inout parameter after the call, and Swift forbids passing the same variable twice as inout to one call, an exclusivity rule that prevents a whole class of aliasing bugs.
Misconception
"map and filter are slower than a loop." For arrays, the optimizer usually produces code as fast as a hand-written loop. Chains like filter then map do create an intermediate array; when that matters, lazy (xs.lazy.filter { ... }.map { ... }) processes elements one at a time. Choose the version that reads best, and measure before optimizing.
Exercises
1. Functions and closures
Warm-upComputationalWhat does this program print?
func describe(_ n: Int, as unit: String = "item", plural: String? = nil) -> String {
n == 1 ? "1 \(unit)" : "\(n) \(plural ?? unit + "s")"
}
print(describe(1), describe(3), describe(2, as: "box", plural: "boxes"))
2. Functions and closures
CoreComputationalGiven func send(_ message: String, to user: String, urgent: Bool = false), which calls compile? Choose every one that does.
3. Functions and closures
CoreComputationalWhat does this program print?
func makeAccumulator() -> (Int) -> Int {
var total = 0
return { amount in
total += amount
return total
}
}
let a = makeAccumulator()
let b = makeAccumulator()
_ = a(5)
_ = b(100)
let c = a
_ = c(10)
print(a(1))
4. Functions and closures
Warm-upComputationalWhat does this print?
let result = (1...6).filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)
print(result)
5. Functions and closures
CoreComputationalWhat does this program print?
var x = 1
let f = { [x] in x * 10 }
let g = { x * 10 }
x = 5
print(f(), g())
6. Functions and closures
StretchComputationalTuples of comparable values compare element by element, like words in a dictionary. What does this program print?
let words = ["kiwi", "fig", "plum", "date", "pear"]
let sortedWords = words.sorted { ($0.count, $0) < ($1.count, $1) }
print(sortedWords.joined(separator: " "))
7. Functions and closures
CoreHumanWhich of these closure parameters must be marked @escaping? List the letters.
- A. The closure passed to
map, called once per element beforemapreturns. - B. A completion handler that a download function stores and calls when the data arrives, seconds later.
- C. A comparison closure passed to
sorted(by:). - D. An event handler that a button object keeps in a property and calls on every tap.
- E. A closure that a function calls three times in a loop and then forgets.
Further reading and resources
- The Swift Programming Language: Functions and ClosuresThe official book's chapters on functions and on closures.
- API Design GuidelinesHow Swift programmers choose names and argument labels. Short, and worth reading in full.
- SE-0279: Multiple trailing closures