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) // 10All lessons in this course
- map and compactMap
- filter and Predicates
- reduce and reduce(into:)
- flatMap and Chaining