reductions(into:_:)
Returns an array containing the accumulated results of combining the elements of the sequence using the given closure.
func reductions<Result>(into initial: Result, _ transform: (inout Result, Element) throws -> Void) 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(into: 0, +)
print(runningTotal)
// prints [0, 1, 3, 6, 10]When reductions(into:_:_) is called, the following steps occur:
The
initialresult is added to an array of results.The
transformclosure is called with theinitialresult 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.