Returns the result of combining the elements of the sequence using the given closure.

SDK

- Xcode 9.0+

Framework

- Swift Standard Library

## Declaration

## Parameters

`initialResult`

The value to use as the initial accumulating value.

`initial`

is passed toResult `next`

the first time the closure is executed.Partial Result `nextPartialResult`

A closure that combines an accumulating value and an element of the sequence into a new accumulating value, to be used in the next call of the

`next`

closure or returned to the caller.Partial Result

## Return Value

The final accumulated value. If the sequence has no elements, the result is `initial`

.

## Discussion

Use the `reduce(_:`

method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of numbers to find their sum or product.

The `next`

closure is called sequentially with an accumulating value initialized to `initial`

and each element of the sequence. This example shows how to find the sum of an array of numbers.

When `numbers`

is called, the following steps occur:

The

`next`

closure is called withPartial Result `initial`

—Result `0`

in this case—and the first element of`numbers`

, returning the sum:`1`

.The closure is called again repeatedly with the previous call’s return value and each element of the sequence.

When the sequence is exhausted, the last value returned from the closure is returned to the caller.

If the sequence has no elements, `next`

is never executed and `initial`

is the result of the call to `reduce(_:`

.

Complexity: O(*n*), where *n* is the length of the sequence.