Menu
Coddy logo textTech

Reduce

Part of the Logic & Flow section of Coddy's Swift journey — lesson 25 of 56.

reduce collapses an entire array into a single value. It's how you sum, multiply, find an extreme, or build a new string-or-array from many elements.

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

The first argument is the initial accumulator. The closure receives the running accumulator and the next element, and returns the new accumulator. Final value of the accumulator is the result.

For arithmetic operators, Swift gives you the symbol-based shorthand:

[1, 2, 3, 4].reduce(0, +)              // 10
[1, 2, 3, 4].reduce(1, *)              // 24

reduce doesn't have to return a number. The accumulator can be any type, you decide:

let sentence = ["hi", "there"].reduce("") { $0 + $1 + "!" }
print(sentence)                    // "hi!there!"
challenge icon

Challenge

Easy

Read a single line of input: a comma-separated list of integers. Using reduce for each, print three lines:

  1. The sum
  2. The product
  3. The maximum value (use a closure that returns the larger of the two arguments, do not call .max())

Assume at least one element. For the maximum, you can use nums[0] as the initial accumulator and reduce the rest of the array.

For input 3,7,2,8,4, the output is:

24
1344
8

Cheat sheet

reduce collapses an array into a single value using an initial accumulator and a closure:

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

Shorthand for arithmetic operators:

[1, 2, 3, 4].reduce(0, +)  // 10
[1, 2, 3, 4].reduce(1, *)  // 24

The accumulator can be any type:

["hi", "there"].reduce("") { $0 + $1 + "!" } // "hi!there!"

To find a maximum using reduce, use the first element as the initial value:

let maxVal = nums.dropFirst().reduce(nums[0]) { $0 > $1 ? $0 : $1 }

Try it yourself

let nums = readLine()!.components(separatedBy: ",").map { Int($0)! }

// TODO: sum, product, max via reduce
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow