Introduction
Swift's Sequence and Collection protocols provide a rich set of functional-style methods that let you transform, filter, and combine collections without writing manual loops. The most common are .map { }, which transforms each element into a new value; .filter { }, which keeps only elements matching a condition; and .reduce(initial) { }, which combines all elements into a single accumulated value. These methods return new collections or values and do not mutate the original, and they are heavily chainable for expressive, readable data pipelines.
Cricket analogy: Turning a list of batsmen's scores into strike rates is .map { }, keeping only those who scored a century is .filter { }, and totaling the whole team's runs into one number is .reduce(0) { } — none of these change the original scorecard, and you can chain filter-then-map-then-reduce in one readable pipeline.
Syntax
let doubled = numbers.map { $0 * 2 }
let evens = numbers.filter { $0 % 2 == 0 }
let sum = numbers.reduce(0) { acc, x in acc + x }
let cleaned = optionalValues.compactMap { $0 }
let sortedAsc = numbers.sorted(by: <)
numbers.forEach { print($0) }Explanation
.map { } applies a closure to every element and returns a new array of the transformed results, preserving the original count and order. .filter { } applies a Boolean closure to each element and returns only the elements for which the closure returned true. .reduce(initial) { acc, x in ... } starts with an initial accumulator value and combines it with each element in turn, ultimately producing a single result such as a sum or concatenated string. .compactMap { } behaves like .map but also removes any nil results, which is especially useful when transforming an array of Optionals into an array of non-optional values. .sorted(by:) returns a new sorted array using a comparison closure, and .forEach { } performs a closure on every element purely for side effects, without producing a new collection. Because each of these returns a value, calls can be chained together, e.g. numbers.filter { ... }.map { ... }.reduce(...).
Cricket analogy: .map { } turns every player's raw score into a strike rate, keeping the same batting order and count; .filter { $0 > 50 } keeps only fifty-plus scores; .reduce(0) { $0 + $1 } totals the innings; .compactMap { } drops any player who didn't bat (nil) from an Optional scores list; .sorted(by:) ranks players by score; and .forEach { print($0) } just announces each score without producing a new list.
Example
let scores = [55, 90, 42, 78, 88, 60]
let passing = scores.filter { $0 >= 60 }
let bonusScores = passing.map { $0 + 5 }
let total = bonusScores.reduce(0) { $0 + $1 }
print(passing)
print(bonusScores)
print(total)
let raw: [String?] = ["10", nil, "20", "abc", nil]
let parsed = raw.compactMap { $0.flatMap { Int($0) } }
print(parsed)Output
[90, 78, 88, 60]
[95, 83, 93, 65]
336
[10, 20]Key Takeaways
.map { }transforms every element and preserves the collection's count..filter { }keeps only elements that satisfy a Boolean condition..reduce(initial) { }combines all elements into a single accumulated value..compactMap { }transforms and simultaneously strips out nil results..sorted(by:)and.forEach { }round out the functional collection toolkit.- These methods are non-mutating and chainable, enabling concise data pipelines.
Practice what you learned
1. What does `.map { }` return relative to the original collection?
2. Which method both transforms elements and removes any resulting nil values?
3. In `numbers.reduce(0) { acc, x in acc + x }`, what does the `0` represent?
4. What does `.filter { $0 % 2 == 0 }` do to an array of integers?
5. Do `.map`, `.filter`, and `.reduce` mutate the original collection?
Was this page helpful?
You May Also Like
Arrays in Swift
Learn how Swift arrays store ordered, mutable collections of values and how to manipulate them safely.
Dictionaries and Sets in Swift
Understand Swift's key-value dictionaries and unique-element sets, including how Hashable powers both.
Closures in Swift
Understand closures as self-contained blocks of functionality that capture and store references to surrounding variables.
Higher-Order Functions in Swift
Explore functions that take other functions or closures as arguments, such as map, filter, and reduce.
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