Swift reduce vs compactMap vs flatMap: Which One Do You Need?
Choose by the shape of the result you want. Use reduce when many elements must become one value, such as a total, a dictionary or a summary, and prefer reduce(into:) when that value is a collection. Use compactMap when each element turns into an optional and you want to keep only the non-nil results. Use flatMap when each element turns into an array (or any sequence) and you want one flat array, and use flatMap on a single optional to chain a step that can fail without ending up with a double optional. Below, the three are compared on real data tasks, with the copying cost hidden in reduce, the mistakes people make when choosing, and a decision checklist.
Difficulty: Beginner to Intermediate
Helpful to know first: closures and the $0 shorthand, optionals, and how map transforms every element of an array.
Related pages cover narrower questions: flatMap vs compactMap looks only at those two, map, filter and reduce teaches the classic trio from the start, and map, filter and sorted covers transforming and ordering. This page is for the moment you have a data task and need to pick between reduce, compactMap and flatMap.
The Verdict: Which Method Fits Your Task
- Use reduce(_:_:) when the result is a single simple value built from every element: a sum, a product, a longest string.
- Use reduce(into:_:) when the result is a dictionary, an array or a set that you fill while walking the elements, such as word counts.
- Use compactMap when the transform can fail (it returns an optional) and failures should simply disappear: parsing strings, looking up IDs, casting.
- Use flatMap on a sequence when each element produces several values and you want them in one array: all items of all orders, all words of all lines.
- Use flatMap on an optional when you have one optional value and the next step also returns an optional.
- Use none of them when a dedicated method says it better: max(), contains(where:), Dictionary(grouping:by:), joined().
reduce, compactMap and flatMap Side by Side
| reduce | compactMap | flatMap (sequence) | flatMap (optional) | |
|---|---|---|---|---|
| Your closure returns | The next accumulated value (or mutates it, with into:) | An optional T? | A sequence of values | An optional U? |
| Result | One value of any type | [T] | One flat array | U? |
| Result count | 1 | 0 to n | Any number | 0 or 1 |
| Typical task | Totals, dictionaries, summaries | Parsing, dropping nils, lookups | Flattening, one-to-many | Chaining failable conversions |
| Stops early | No | No | No | Skips the closure when nil |
| Cost | O(n), or O(n²) if a collection is copied each step | O(n) | O(total elements produced) | One call |
The Differences, Task by Task
Summing a cart: reduce(_:_:)
reduce starts from an initial value and folds each element into it. Swift has no built-in sum() on arrays, so reduce(0, +), or reduce with a closure, is the normal way to total things:
struct LineItem {
let name: String
let price: Double
let quantity: Int
}
let cart = [
LineItem(name: "Notebook", price: 4.5, quantity: 3),
LineItem(name: "Pen", price: 1.25, quantity: 4),
LineItem(name: "Stapler", price: 12, quantity: 1)
]
let itemCount = cart.reduce(0) { $0 + $1.quantity }
let total = cart.reduce(0.0) { $0 + $1.price * Double($1.quantity) }
print(itemCount) // Output: 8
print(total) // Output: 30.58 30.5
$0 is the running result and $1 is the current element. The type of the initial value decides the result type, so 0 gives an Int and 0.0 gives a Double. For real money, use Decimal instead of Double to avoid rounding errors.
Counting words into a dictionary: reduce(into:_:)
When the result is a collection, reduce(into:) hands your closure the accumulator as an inout parameter. You change it in place and return nothing:
let words = ["the", "cat", "and", "the", "hat", "and", "the", "bat"]
let counts = words.reduce(into: [String: Int]()) { counts, word in
counts[word, default: 0] += 1
}
for (word, count) in counts.sorted(by: { $0.key < $1.key }) {
print(word, count)
}
// Output:
// and 2
// bat 1
// cat 1
// hat 1
// the 3and 2 bat 1 cat 1 hat 1 the 3
The loop sorts before printing because a dictionary has no fixed order. When you only need to group elements, not count or combine them, Dictionary(grouping:by:) is shorter:
let names = ["Ana", "Ben", "Alex", "Cleo", "Bea"]
let byInitial = Dictionary(grouping: names, by: { $0.prefix(1) })
print(byInitial["A", default: []]) // Output: ["Ana", "Alex"]
print(byInitial["B", default: []]) // Output: ["Ben", "Bea"]["Ana", "Alex"] ["Ben", "Bea"]
If you build a dictionary from key-value pairs instead, note that Dictionary(uniqueKeysWithValues:) crashes on a repeated key with Fatal error: Duplicate values for key: 'a'; use Dictionary(_:uniquingKeysWith:) or reduce(into:) when keys can repeat. More on these initializers in Swift dictionaries.
Dropping invalid values: compactMap
compactMap runs a transform that returns an optional and keeps only the values that are not nil. Compare it with map on the same input:
let rawAges = ["31", "unknown", "45", "", "28"]
print(rawAges.map { Int($0) })
// Output: [Optional(31), nil, Optional(45), nil, Optional(28)]
print(rawAges.compactMap { Int($0) })
// Output: [31, 45, 28][Optional(31), nil, Optional(45), nil, Optional(28)] [31, 45, 28]
map keeps one result per element, so the failures stay as nil and the type is [Int?]. compactMap gives [Int]. The same tool works for lookups that can miss, and compactMap { $0 } removes the nils from an array that already holds optionals:
let usersByID = [1: "Maya", 2: "Jordan", 4: "Sam"]
let selectedIDs = [4, 3, 1]
let selectedNames = selectedIDs.compactMap { usersByID[$0] }
print(selectedNames) // Output: ["Sam", "Maya"]
let scores: [Int?] = [90, nil, 75, nil]
print(scores.compactMap { $0 }) // Output: [90, 75]["Sam", "Maya"] [90, 75]
ID 3 has no user, so it is skipped and the order of the remaining IDs is kept. If you need to know which elements failed, compactMap is the wrong tool: it drops that information.
Flattening nested arrays: flatMap on a sequence
Use flatMap when each element gives you an array and you want all of them in one array. A key path works as the closure:
struct Order {
let id: Int
let items: [String]
}
let orders = [
Order(id: 1, items: ["tea", "milk"]),
Order(id: 2, items: []),
Order(id: 3, items: ["bread"])
]
let allItems = orders.flatMap(\.items)
print(allItems) // Output: ["tea", "milk", "bread"]
let lines = ["red green", "blue"]
let colors = lines.flatMap { $0.split(separator: " ") }
print(colors) // Output: ["red", "green", "blue"]["tea", "milk", "bread"] ["red", "green", "blue"]
With map, the first result would be [["tea", "milk"], [], ["bread"]]. flatMap removes exactly one level of nesting, and empty arrays simply add nothing. If you already have an array of arrays and no transform, joined() does the same job.
Chaining a failable step on one optional: Optional.flatMap
Optionals have their own map and flatMap. The difference shows up when the transform itself returns an optional, like Int(_:) on a string:
let input: String? = "42"
let mapped = input.map { Int($0) }
let flat = input.flatMap { Int($0) }
print(type(of: mapped)) // Output: Optional<Optional<Int>>
print(type(of: flat)) // Output: Optional<Int>
print(flat ?? 0) // Output: 42Optional<Optional<Int>> Optional<Int> 42
map wraps the Int? in another optional, giving Int??. flatMap returns the closure's optional as it is. If input is nil, neither runs the closure. For longer chains on optional values, optional chaining and if let are often easier to read.
Performance: Why reduce(into:) Beats reduce for Collections
In reduce(_:_:), the closure receives the running result as a constant and must return a new one. For an Int that costs nothing. For an array, result + [n] builds a new array and copies every element collected so far, on every step. With n elements that is about n²/2 element copies, so 10,000 elements mean roughly 50 million copies. reduce(into:) passes the accumulator inout, so appending changes one array in place and the whole run is O(n).
let numbers = Array(1...10)
// Copies the growing array on every step: O(n²)
let slow = numbers.reduce([Int]()) { result, n in
n.isMultiple(of: 2) ? result + [n * n] : result
}
// Mutates one array in place: O(n)
let fast = numbers.reduce(into: [Int]()) { result, n in
if n.isMultiple(of: 2) { result.append(n * n) }
}
// Clearer for this task: filter and transform in one pass
let squares = numbers.compactMap { $0.isMultiple(of: 2) ? $0 * $0 : nil }
print(slow == fast, fast == squares) // Output: true true
print(squares) // Output: [4, 16, 36, 64, 100]true true [4, 16, 36, 64, 100]
All three give the same answer. The last line is the point: when a "reduce into an array" only filters and transforms, compactMap (or filter plus map) says it more directly.
Other facts worth knowing:
- None of the three methods stops early. reduce visits every element even when the answer is already known. To test "is any element…" or "are all elements…", use contains(where:) and allSatisfy, which stop at the first decisive element.
- A chain such as flatMap, then compactMap, then reduce builds an intermediate array at each step. Adding .lazy at the start removes them; see lazy collections.
- joined() returns a lazy view over the nested arrays, while flatMap builds a new array right away.
- For a few hundred elements none of this is measurable in practice. Pick the version that reads best.
Here is a lazy version of a full pipeline. It flattens the items of every order, looks up each price, and adds them up without building the in-between arrays:
struct Order {
let id: Int
let items: [String]
}
let prices = ["tea": 2.5, "milk": 1.2, "bread": 3.0]
let orders = [
Order(id: 1, items: ["tea", "milk"]),
Order(id: 2, items: []),
Order(id: 3, items: ["bread", "cake"])
]
let revenue = orders.lazy
.flatMap(\.items)
.compactMap { prices[$0] }
.reduce(0, +)
print(revenue) // Output: 6.76.7
"cake" has no price, so compactMap drops it, and each method does the one job it is best at.
Common Mistakes When Choosing Between Them
Using flatMap to remove nils
Before Swift 4.1, the nil-removing method on sequences was also called flatMap, and old answers online still use it.
Problem: The closure returns an optional, so this calls the old overload. It still works, but the compiler warns 'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value, and readers expect flatMap to mean flattening.
let inputs = ["4", "x", "15"]
let numbers = inputs.flatMap { Int($0) }
print(numbers)[4, 15]
Fix: Use compactMap whenever the closure returns an optional.
let inputs = ["4", "x", "15"]
let numbers = inputs.compactMap { Int($0) }
print(numbers) // Output: [4, 15][4, 15]
The corrected version works the same way without the warning, and its name tells the reader that nils are dropped.
Using map when the transform can fail
map keeps every result, including the failures.
Problem: Int($0) returns Int?, so ages is [Int?] and the call fails to compile: cannot convert value of type '[Int?]' to expected argument type '[Int]'.
func average(_ values: [Int]) -> Double {
Double(values.reduce(0, +)) / Double(values.count)
}
let ages = ["31", "unknown", "45"].map { Int($0) }
print(average(ages))error: cannot convert value of type '[Int?]' to expected argument type '[Int]'
Fix: Use compactMap so the invalid entries are dropped and the type is [Int].
func average(_ values: [Int]) -> Double {
Double(values.reduce(0, +)) / Double(values.count)
}
let ages = ["31", "unknown", "45"].compactMap { Int($0) }
print(average(ages)) // Output: 38.038.0
The corrected version works because only the two valid ages reach average. Guard against an empty array in real code, since dividing by a count of 0 gives nan.
Mutating the accumulator in plain reduce
Building a dictionary with reduce(_:_:) and changing the running result inside the closure looks natural, but that result is a constant.
Problem: The compiler rejects the change with left side of mutating operator isn't mutable: 'result' is a 'let' constant. Copying it into a var would compile, but it copies the whole dictionary on every step.
let words = ["apple", "kiwi", "apple"]
let counts = words.reduce([String: Int]()) { result, word in
result[word, default: 0] += 1
return result
}error: left side of mutating operator isn't mutable: 'result' is a 'let' constant
Fix: Switch to reduce(into:), whose accumulator is inout.
let words = ["apple", "kiwi", "apple"]
let counts = words.reduce(into: [String: Int]()) { result, word in
result[word, default: 0] += 1
}
print(counts["apple", default: 0], counts["kiwi", default: 0]) // Output: 2 12 1
The corrected version works because into: lets the closure change one dictionary in place instead of returning a new one.
Calling flatMap on a property that is a String
String is a sequence of characters, so flatMap happily flattens it.
Problem: Each post has one tag, a String. flatMap splits every tag into characters and returns [Character], which prints ["s", "w", "i", "f", "t", "i", "o", "s"].
struct Post {
let title: String
let tag: String
}
let posts = [Post(title: "Intro", tag: "swift"), Post(title: "Lists", tag: "ios")]
let tags = posts.flatMap { $0.tag }
print(tags)["s", "w", "i", "f", "t", "i", "o", "s"]
Fix: Use map when each element produces exactly one value. Keep flatMap for properties that are arrays.
struct Post {
let title: String
let tag: String
}
let posts = [Post(title: "Intro", tag: "swift"), Post(title: "Lists", tag: "ios")]
let tags = posts.map(\.tag)
print(tags) // Output: ["swift", "ios"]["swift", "ios"]
The corrected version works because map keeps each tag whole, one result per post.
Expecting flatMap to flatten every level
Data from JSON is often nested more than once.
Problem: flatMap { $0 } removes only the outer level, so this prints [[1], [2], [3]], still an array of arrays.
let nested = [[[1], [2]], [[3]]]
print(nested.flatMap { $0 })[[1], [2], [3]]
Fix: Flatten once per level of nesting.
let nested = [[[1], [2]], [[3]]]
print(nested.flatMap { $0 }.flatMap { $0 }) // Output: [1, 2, 3][1, 2, 3]
The corrected version works because each flatMap removes one level, and there are two levels to remove.
Predict the Output
let raw = ["1", "x", "3"]
let a = raw.map { Int($0) }
let b = raw.compactMap { Int($0) }
let c = [raw, ["4"]].flatMap { $0 }
print(a.count, b.count, c.count)
print(b.reduce(10, +))What does this print?
Show answer
It prints 3 2 4 and then 14.
- a has 3 elements: map keeps one result per input, including the nil for "x".
- b has 2 elements: compactMap drops the nil.
- c has 4 elements: flatMap joins ["1", "x", "3"] and ["4"] into one array of strings. Nothing is parsed, so "x" stays.
- reduce(10, +) starts at 10, not 0, and adds 1 and 3.
Decision Checklist: reduce, compactMap or flatMap?
- If you need one number, string or Boolean from all the elements, use reduce(_:_:), unless max(), min(), contains(where:) or allSatisfy already says it.
- If you are filling a dictionary, array or set, use reduce(into:), or Dictionary(grouping:by:) when you only group.
- If your transform returns an optional and failures should vanish, use compactMap.
- If you need to know which elements failed, use map and keep the optionals, or a loop that collects errors.
- If each element gives an array and you want one array, use flatMap; if you already have [[T]], joined() also works.
- If each element gives exactly one value, use map, never flatMap.
- If you have one optional and the next step returns an optional, use Optional.flatMap or if let.
- If the chain is long and the data is large, add .lazy or write one loop.
Summary
- Pick the method from the result's shape: one value (reduce), fewer elements with no nils (compactMap), or one flat array (flatMap).
- Use reduce(into:) for collection results; reduce with + [element] copies the array on every step and is O(n²).
- compactMap replaced the nil-removing flatMap in Swift 4.1; the old form now gives a deprecation warning.
- flatMap removes one level of nesting, and on a String it produces characters.
- On an optional, flatMap avoids T?? when the transform can fail.
Next, learn how .lazy runs these chains without intermediate arrays in Swift lazy collections.