Combining an Arrays elements with reduce combine

suggest change

reduce(_:combine:) can be used in order to combine the elements of a sequence into a single value. It takes an initial value for the result, as well as a closure to apply to each element – which will return the new accumulated value.

For example, we can use it to sum an array of numbers:

let numbers = [2, 5, 7, 8, 10, 4]

let sum = numbers.reduce(0) {accumulator, element in
    return accumulator + element
}

print(sum) // 36

We’re passing 0 into the initial value, as that’s the logical initial value for a summation. If we passed in a value of N, the resulting sum would be N + 36. The closure passed to reduce has two arguments. accumulator is the current accumulated value, which is assigned the value that the closure returns at each iteration. element is the current element in the iteration.

As in this example, we’re passing an (Int, Int) -> Int closure to reduce, which is simply outputting the addition of the two inputs – we can actually pass in the \+ operator directly, as operators are functions in Swift:

let sum = numbers.reduce(0, combine: +)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents