Introduction
A higher-order function is a function that either takes one or more functions or closures as parameters, returns a function, or both. Swift's standard library ships with several higher-order functions on collections that make it possible to write concise, expressive, and idiomatic code without manually writing loops. The most common examples are map, filter, reduce, sorted(by:), compactMap, and forEach.
Cricket analogy: A team analyst's function that accepts "apply this filtering strategy" as an input, like passing in a spin-friendly-pitch strategy closure, is a higher-order function, much like map, filter, and reduce accept closures to process ball-by-ball data.
Syntax
array.map { transform in ... }
array.filter { predicate in ... }
array.reduce(initialResult) { partial, element in ... }
array.sorted(by: { a, b in ... })
array.compactMap { transform in ... }
array.forEach { element in ... }Explanation
map transforms each element of a collection and returns a new collection of the transformed values. filter returns a new collection containing only the elements that satisfy a given condition (predicate). reduce combines all elements into a single value using an accumulator closure. compactMap behaves like map but also strips out nil results, unwrapping optionals in the process. forEach runs a closure on every element purely for side effects, without producing a new collection. sorted(by:) returns a new sorted array based on a comparison closure. Because these functions accept closures as arguments, they qualify as higher-order functions, and using trailing closure syntax with them is idiomatic Swift.
Cricket analogy: map converts each ball's raw speed into km/h across a list of deliveries; filter keeps only sixes from an over; reduce totals a batsman's runs across an innings using an accumulator, all without writing a manual loop.
Example
let numbers = [1, 2, 3, 4, 5, 6]
let doubled = numbers.map { $0 * 2 }
let evens = numbers.filter { $0 % 2 == 0 }
let sum = numbers.reduce(0) { $0 + $1 }
let strings = ["1", "two", "3"]
let parsed = strings.compactMap { Int($0) }
print(doubled)
print(evens)
print(sum)
print(parsed)Output
[2, 4, 6, 8, 10, 12]
[2, 4, 6]
21
[1, 3]Key Takeaways
- Higher-order functions take or return other functions or closures.
maptransforms elements;filterkeeps elements matching a predicate.reducecombines all elements into a single accumulated value.compactMapmaps and removesnilresults, unwrapping optionals.forEachperforms a side-effecting action on each element without returning a new collection.- These functions are heavily used in idiomatic Swift instead of manual for-loops.
Practice what you learned
1. What defines a higher-order function?
2. Which higher-order function returns a new array containing only elements matching a condition?
3. What does `reduce` do?
4. How does `compactMap` differ from `map`?
5. Which higher-order function is used purely for side effects, without producing a new collection?
Was this page helpful?
You May Also Like
Closures in Swift
Understand closures as self-contained blocks of functionality that capture and store references to surrounding variables.
Functions in Swift
Learn how to declare, call, and label the parameters of reusable blocks of code called functions in Swift.
Collection Operations in Swift (map, filter, reduce)
Master Swift's functional-style collection operations — map, filter, reduce, compactMap, and sorted.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics