Returns the result of combining the elements of the sequence using the given closure.
SDK
- Xcode 11.0+
Framework
- Swift Standard Library
Declaration
Parameters
initialResult
The value to use as the initial accumulating value.
updateAccumulatingResult
A closure that updates the accumulating value with an element of the sequence.
Return Value
The final accumulated value. If the sequence has no elements, the result is initial
.
Discussion
Use the reduce(into:
method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of integers to filter adjacent equal entries or count frequencies.
This method is preferred over reduce(_:
for efficiency when the result is a copy-on-write type, for example an Array or a Dictionary.
The update
closure is called sequentially with a mutable accumulating value initialized to initial
and each element of the sequence. This example shows how to build a dictionary of letter frequencies of a string.
When letters
is called, the following steps occur:
The
update
closure is called with the initial accumulating value—Accumulating Result [:]
in this case—and the first character ofletters
, modifying the accumulating value by setting1
for the key"a"
.The closure is called again repeatedly with the updated accumulating value and each element of the sequence.
When the sequence is exhausted, the accumulating value is returned to the caller.
If the sequence has no elements, update
is never executed and initial
is the result of the call to reduce(into:
.
Complexity: O(n), where n is the length of the sequence.