reductions(_:_:)
Returns an array containing the accumulated results of combining the elements of the sequence using the given closure.
func reductions<Result>(_ initial: Result, _ transform: (Result, Element) throws -> Result) rethrows -> [Result]
Parameters
Returns
An array of the initial value followed by the reduced elements.
This can be seen as applying the reduce function to each element and providing the initial value followed by these results as a sequence.
let runningTotal = [1, 2, 3, 4].reductions(0, +)
print(runningTotal)
// prints [0, 1, 3, 6, 10]
When reductions(_:_:)
is called, the following steps occur:
The
initial
result is added to an array of results.The
transform
closure is called with theinitial
result and the first element of the sequence, appending the result to the array.The closure is called again repeatedly with the updated accumulating result and each element of the sequence, adding each result to the array.
When the sequence is exhausted, the results array is returned to the caller.
If the sequence has no elements, transform
is never executed and an array containing only the initial
result is returned.