Fork me on GitHub

How Do I Use Reduce in Swift?

reduce returns the result of combining the elements of a sequence using the given closure.

[1, 2, 3, 4, 5].reduce(0, +) // 15

find the sum of primitives

["Hello", " ", "world, "!"].reduce("", +) // Hello world!

works on other primitives as well:

[1, 2, 3, 4, 5].reduce(0, +) // 15

which is equivalent and shorthand to:

[1, 2, 3, 4, 5].reduce(0, { $0 + $1 }) // 15

which is also equivalent and shorthand to:

[1, 2, 3, 4, 5].reduce(0, { x, y in x + y }) // 15

find the sum of properties

struct Person { let age: Int }
let people = [Person(age: 1), Person(age: 2), Person(age: 3), Person(age: 4), Person(age: 5)]
people.reduce(0, { accumulator, person in accumulator + person.age }) // 15

or generalized using Key Paths: (source)

extension Sequence {
  func sum<T: Numeric>(for keyPath: KeyPath<Element, T>) -> T {
    return reduce(0) { sum, element in
        sum + element[keyPath: keyPath]
    }
  }
}
people.sum(for: \.age) // 15

find the frequency of elements

example from the documentation:

"abracadabra".reduce(into: [:]) { counts, letter in
  counts[letter, default: 0] += 1
}
// ["b": 2, "r": 2, "c": 1, "d": 1, "a": 5]

Other more in-depth articles:

  • Reducers in Swift - Swift by Sundell
  • reduce(into:_:) - Apple documentation