Swift Higher-Order Functions
A higher-order function is a function that takes another function (usually a closure) as a parameter, or returns one. Swift's collections come with a family of them — map, filter, reduce, compactMap, flatMap, sorted(by:), forEach and more. They let you describe what you want to do with the data instead of writing the loop by hand.
map: transform every element
map calls your closure once per element and collects the results into a new array. The original array is not changed.
import Foundation
let prices = [4.5, 12.0, 7.25]
let withTax = prices.map { $0 * 1.1 }
let labels = prices.map { price in "$\(price)" }
print(labels)
print(withTax.map { String(format: "%.2f", $0) })
print(prices.count == withTax.count)["$4.5", "$12.0", "$7.25"]
["4.95", "13.20", "7.98"]
true
String(format:) comes from Foundation, hence the import. The result type can differ from the input type: here labels is [String] even though prices is [Double].
filter: keep what matches
filter keeps the elements for which the closure returns true.
let scores = [72, 95, 48, 88, 61, 100]
let passed = scores.filter { $0 >= 60 }
let perfect = scores.filter { $0 == 100 }
print("Passed:", passed)
print("Perfect:", perfect.count)Passed: [72, 95, 88, 61, 100]
Perfect: 1
reduce: combine into one value
reduce starts with an initial value and folds each element into it. It is perfect for sums, products, or building up a single result.
let cart = [3, 1, 4, 1, 5]
let total = cart.reduce(0, +)
let biggest = cart.reduce(Int.min) { max($0, $1) }
let sentence = ["Swift", "is", "fun"].reduce("") { result, word in
result.isEmpty ? word : result + " " + word
}
print(total)
print(biggest)
print(sentence)14
5
Swift is fun
Tip: Passing an operator like
+works because operators are just functions:+has the type(Int, Int) -> Int, exactly whatreduceexpects.
compactMap and flatMap
| Function | What it does | Example result |
|---|---|---|
map |
Transform each element | [1, 2] → ["1", "2"] |
compactMap |
Transform and drop nil results |
["1", "x"] → [1] |
flatMap |
Transform each element into a sequence and flatten | [[1, 2], [3]] → [1, 2, 3] |
filter |
Keep matching elements | [1, 2, 3] → [2] |
reduce |
Combine into one value | [1, 2, 3] → 6 |
let input = ["42", "seven", "8", "", "15"]
let numbers = input.compactMap { Int($0) }
print(numbers)
let teams = [["Ana", "Ben"], ["Chloe"], ["Dev", "Eli"]]
let everyone = teams.flatMap { $0 }
print(everyone)[42, 8, 15]
["Ana", "Ben", "Chloe", "Dev", "Eli"]
Int("seven") returns nil, so compactMap simply skips it — no unwrapping needed.
Chaining
Because each function returns a new collection, you can chain them into a small data pipeline. Read it top to bottom like a recipe:
struct Order {
let customer: String
let amount: Double
let paid: Bool
}
let orders = [
Order(customer: "Mia", amount: 120, paid: true),
Order(customer: "Leo", amount: 35, paid: false),
Order(customer: "Zoe", amount: 80, paid: true),
Order(customer: "Ian", amount: 210, paid: true),
]
let report = orders
.filter { $0.paid }
.sorted { $0.amount > $1.amount }
.map { "\($0.customer): \($0.amount)" }
report.forEach { print($0) }
print("Revenue:", orders.filter(\.paid).reduce(0) { $0 + $1.amount })Ian: 210.0
Mia: 120.0
Zoe: 80.0
Revenue: 410.0
\.paid is a key path. Swift lets you pass a key path wherever a closure (Order) -> Bool is expected, which keeps simple pipelines short.
Writing your own higher-order function
Any function can accept a closure parameter. Here is a tiny applyTwice, plus a function that returns a function:
func applyTwice(_ value: Int, _ transform: (Int) -> Int) -> Int {
transform(transform(value))
}
func makeMultiplier(by factor: Int) -> (Int) -> Int {
return { $0 * factor }
}
print(applyTwice(3) { $0 + 10 })
let triple = makeMultiplier(by: 3)
print(applyTwice(2, triple))23
18
Note: For very large collections,
lazy(for examplenumbers.lazy.map { … }.filter { … }) avoids building intermediate arrays — elements are processed only when the result is actually used.
Test yourself
What does ["1", "a", "3"].compactMap { Int($0) } return?
- [1, nil, 3]
- [1, 3]
- ["1", "3"]
- It does not compile
Which call adds up all values in nums?
- nums.map(+)
- nums.filter(0, +)
- nums.reduce(0, +)
- nums.flatMap(+)
Does map change the original array?
- Yes, always
- Only for
vararrays - No, it returns a new array
- Only if the closure uses
$0