reductions(_:)
Returns an array containing the accumulated results of combining the elements of the sequence using the given closure.
func reductions(_ transform: (Element, Element) throws -> Element) rethrows -> [Element]
Parameters
- transform
A closure that combines the previously reduced result and the next element in the receiving sequence.
Returns
An array of 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(+)
print(runningTotal)
// prints [1, 3, 6, 10]
When reductions(_:)
is called, the following steps occur:
The
transform
closure is called with the first and second elements of the sequence, appending the result to an array of results.The closure is called again repeatedly with the updated accumulating result and the next 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 empty array is returned.
If the sequence has one element, transform
is never executed and an array containing only that first element is returned.