#77: reduce(into:) in Swift

If your reduction builds a mutable result like an array or dictionary, reduce(into:) is often a better fit than plain reduce.

let words = ["swift", "bite", "swift"]
let counts = words.reduce(into: [:]) { partial, word in
    partial[word, default: 0] += 1
}

The result is mutated in place instead of creating a brand new copy at every step.

It is a small API difference, but for collection-building code it can be both clearer and more efficient.


I'm also on Twitter and GitHub.

Subscribe via RSS.