Swiftly

Swift 5.1 references for busy coders

reduce

reduce is a functional method that returns the result of combining the elements of a sequence using a given closure. It takes in two parameters:

reduce an array of Ints

let numbers = [1, 2, 3, 4]
let numbersSum = numbers.reduce(0) {
  $0 + $1
}
let numbersProduct = numbers.reduce(1) {
  $0 * $1
}
print(numbersSum) // 10
print(numbersProduct) // 24

The example above can be shortened to the following:

let numbers = [1, 2, 3, 4]
let numbersSum = numbers.reduce(0, +)
let numbersProduct = numbers.reduce(1, *)
print(numbersSum) // 10
print(numbersProduct) // 24