reduce(_:_:)— pure, functional, returns a new value
This version works by creating a new value at each step.
let sum = [1, 2, 3].reduce(0) { partial, value in
partial + value
}Great for: • computing a single value (sum, product, booleans) • purely functional operations • code clarity when mutation isn’t needed
Caveat: • Not as performant when you’re building up a larger structure (arrays, dictionaries) because it copies all intermediate results.
⸻
reduce(into:_:)— mutating, more efficient
This version gives you a mutable accumulator to update in place:
let doubled = [1, 2, 3].reduce(into: []) { result, value in
result.append(value * 2)
}Why it matters: • More efficient for building collections • Avoids constant copying • Often the right choice in algorithms where you accumulate arrays, dictionaries, or sets
⸻
When this matters in interviews
You’ll see problems where you need to build something step-by-step—like frequency maps, grouped values, or deduplicating data.
Using reduce(into:) cleanly demonstrates: • you understand Swift’s value-semantics • you know how to avoid unnecessary copying • you can write expressive, efficient code under pressure
It’s one of those “small but senior” differentiators.
⸻
Bonus: The Dictionary Default-Value Subscript
A lot of candidates never use this—even though it massively simplifies counting and grouping logic:
var counts: [Int: Int] = [:]
for num in [1, 2, 3, 1, 2] {
counts[num, default: 0] += 1
}Why this matters: • Removes optional handling • No need for if let, guard, or manual initialization • Essential for fast solutions to frequency-based interview problems
In fact, for problems like 3Sum, building a frequency map becomes significantly cleaner with this syntax.
⸻
If you’re preparing for Swift-based interviews, mastering these small patterns makes your code faster, safer, and more expressive—while also signaling a strong command of the language.
Happy coding 👨💻🚀