0Pricing
Swift Academy · Lesson

reduce and reduce(into:)

Aggregate collections into a single value.

What Is reduce?

reduce collapses a whole sequence into a single value by repeatedly combining an accumulator with each element.

  • You give a starting value
  • And a closure (accumulator, element) -> accumulator

Summing with reduce

The classic example — add everything up:

let nums = [1, 2, 3, 4]
let total = nums.reduce(0) { acc, x in acc + x }
print(total)  // 10

All lessons in this course

  1. map and compactMap
  2. filter and Predicates
  3. reduce and reduce(into:)
  4. flatMap and Chaining
← Back to Swift Academy