skip to content

In a Swift analytics pipeline, why is reduce(into:_:) preferred over reduce(_:_:) when counting a day's events into a Dictionary?

level: middleimportance: should knowfreq 50%

answer

  1. returned value vs inout
  2. copy-on-write buffer
  3. one copy per element
  4. quadratic overall

basics

~20 s

With reduce(::) the closure must return a new Dictionary, and mutating a copy of a buffer the standard library still holds copies it on every element; reduce(into:_:) passes the Dictionary inout and mutates it in place.

solid answer

~40 s

`reduce(_:_:)` calls `nextPartialResult(accumulator, element)` and stores what it returns. To add a key you write `var copy = counts`, mutate, and return `copy`, but the standard library's `accumulator` still references the same storage, so the mutation triggers a copy-on-write copy of the whole dictionary every time. The work grows with events times distinct names, which is quadratic when most names are distinct. `reduce(into:_:)` hands the closure an `inout` accumulator, so `counts[event.name, default: 0] += 1` mutates uniquely owned storage in place. The doc comment says it is preferred for efficiency when the result is a copy-on-write type such as `Array` or `Dictionary`. For a scalar total, `reduce(0) { $0 + $1.durationMs }` is fine, and since Swift 6.0 `count(where:)` counts matches without building an array.

code

swift · 23 lines
swift
struct Event {
    let name: String
    let durationMs: Int
}

let today = [
    Event(name: "view", durationMs: 120),
    Event(name: "purchase", durationMs: 900),
    Event(name: "view", durationMs: 80),
]

// Preferred: the dictionary is mutated in place through an inout parameter.
let countsByName = today.reduce(into: [String: Int]()) { counts, event in
    counts[event.name, default: 0] += 1
}

// Fine: the accumulator is a plain Int, so returning a new value costs nothing.
let totalMs = today.reduce(0) { $0 + $1.durationMs }

// Swift 6.0 and later: count matches without building a filtered array.
let purchases = today.count(where: { $0.name == "purchase" })

print(countsByName["view"]!, totalMs, purchases)   // 2 1100 1

go deeper

for a junior

Recall the two signatures: reduce returns the new accumulator, reduce(into:) mutates an inout one. Use reduce for sums and reduce(into:) for dictionaries and arrays.

for a middle

Explain how returning a mutated copy collides with copy-on-write, making the fold quadratic when keys keep growing, and why inout avoids the copy.

for a senior

Spot the var-copy-return pattern in review, measure before trusting the optimizer, and pick count(where:), contains(where:) or a grouping initializer when they say more.

for a principal

Agree on a team idiom for aggregation code so hot paths over large logs do not hide quadratic folds behind correct-looking results.

## Two ways to fold a sequence **Reducing** (also called folding) combines all elements of a sequence into one value. Swift's `Sequence` offers two methods, both documented as O(*n*) in the length of the sequence, both returning the initial value unchanged when the sequence is empty. | | `reduce(_:_:)` | `reduce(into:_:)` | |---|---|---| | Closure signature | `(Result, Element) -> Result` | `(inout Result, Element) -> Void` | | How the accumulator changes | the closure returns a new value | the closure mutates it in place | | Best for | scalars: sums, maxima, flags | copy-on-write values: `Array`, `Dictionary`, `Set` | The O(*n*) in the documentation counts closure calls. It says nothing about what each call costs, and that is where the two differ. ## Why reduce(_:_:) copies the dictionary The standard library's implementation of `reduce(_:_:)` keeps a local `accumulator` and does `accumulator = try nextPartialResult(accumulator, element)` for each element. Counting a day's events by name looks like this: 1. The closure receives `counts`, a `let` parameter, so it writes `var copy = counts`. 2. At that moment two variables, `copy` and the library's `accumulator`, share one dictionary buffer. 3. `copy[event.name, default: 0] += 1` is a mutation of shared storage, so **copy-on-write** copies the whole buffer first. 4. The closure returns `copy`, which replaces `accumulator`, and the old buffer is released. Each step copies the whole dictionary, so the total work is the number of events times the dictionary's size: quadratic when the keys keep growing, merely wasteful when there are only a handful of names. Measured with the Swift 6.4 compiler, doubling the number of distinct event names from 4,000 to 8,000 roughly quadrupled the time of this version, with or without `-O`, while `reduce(into:_:)` stayed linear. The optimizer can sometimes remove such a copy (an array built with `$0 + [$1]` was linear under `-O` in the same test but quadratic at `-Onone`), but you cannot rely on it. ## Why reduce(into:_:) does not `reduce(into:_:)` stores the initial value in a local variable and passes it to the closure **`inout`**. Inside the closure `counts` refers to storage nobody else holds, so `counts[event.name, default: 0] += 1` updates it in place, with the dictionary's normal amortized cost per insert. The method's doc comment says so directly: it is preferred over `reduce(_:_:)` for efficiency when the result is a copy-on-write type, for example an `Array` or a `Dictionary`. Its own example builds a letter-frequency dictionary. ## Choosing the right tool for each analytics question - **Total time spent**: `today.reduce(0) { $0 + $1.durationMs }`. An `Int` has no buffer to copy, so the returning form is clear and cheap. - **Counts per event name**: `reduce(into: [String: Int]())` with the `subscript(_:default:)` increment. - **One count of matches**: `today.count(where:)`, added in **Swift 6.0**, which avoids the intermediate array that `filter(_:).count` builds. - **Events grouped into arrays by name**: `Dictionary(grouping:by:)` does it in one call; that initializer belongs with the Swift lesson on dictionaries. - **Is there any purchase, are all events timed**: `contains(where:)` and `allSatisfy(_:)` stop at the first decisive element instead of folding the whole log. ## Reading a reduce in code review A few habits catch most problems: - A `var copy = $0` followed by a mutation and `return copy` inside `reduce(_:_:)` is the quadratic pattern; rewrite it with `reduce(into:_:)`. - A closure that appends to an outer `var` from inside `map` or `reduce` is a loop in disguise; a `for`-`in` loop or `reduce(into:_:)` states the intent. - The result for an empty log is the initial value, so `[:]` and `0` must be the right answers for a day with no events. - The closure of `reduce(into:_:)` returns nothing; writing `return counts` inside it is a compile error, which is a quick way to tell the two forms apart when reading unfamiliar code. ## Why this matters beyond dictionaries The same reasoning applies to any accumulator with copy-on-write storage: building an `Array` with `$0 + [$1]`, a `Set` with `$0.union([$1])`, or a `String` with `$0 + piece` inside `reduce(_:_:)`. Each returning step may allocate a fresh buffer that is one element larger. For small inputs nobody notices; over a full day's event log the difference between linear and quadratic shows up in profiles, so the habit of reaching for `reduce(into:_:)` with collection accumulators is cheap insurance.

  • Is `reduce(_:_:)` ever the better choice?
    Yes, when the accumulator is a small value with no shared buffer, such as an `Int` sum, a `Double` maximum or a `Bool`. Returning a new value is then clear and free. It also reads well when the combining step is an existing function, as in `reduce(0, +)`.
  • How do you count only the purchase events, and what does `filter(_:).count` cost by comparison?
    From Swift 6.0, `today.count(where: { $0.name == "purchase" })` walks the log once and returns an `Int`. `today.filter { $0.name == "purchase" }.count` gives the same number but first allocates an array of every matching event, then reads its count.

  • reduce(_:_:) is always O(n), so building a dictionary with it is linear
  • reduce(into:_:) is only syntax sugar with identical performance
  • The compiler always optimizes away the dictionary copy in reduce
  • Dictionary's subscript(_:default:) increment is a linear-time operation
  • filter(_:).count counts matches without allocating anything

Assumes Swift 6.4; count(where:) exists from Swift 6.0 (SE-0220), while reduce(into:_:) dates from Swift 4.0.