Skip to content

Instantly share code, notes, and snippets.

@scott-lydon
Created December 3, 2025 06:26
Show Gist options
  • Select an option

  • Save scott-lydon/3a0f3422501de74cd00951c27dc5fe1c to your computer and use it in GitHub Desktop.

Select an option

Save scott-lydon/3a0f3422501de74cd00951c27dc5fe1c to your computer and use it in GitHub Desktop.
  1. 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.

  1. 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 👨‍💻🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment