Exploring how to use reduce in Swift

Juan Navas
2 min readNov 3, 2017

Every time I’ve tried to learn how to use reduce, I have usually found the same examples.

The one where it’s used to combine numeric elements of an array

Likewise, we can combine different strings into a single one

Basically reduce iterates over a collection, taking 2 arguments, an initial value and a closure which applies a transformation to that value.

This closure provides two parameters, the partial result obtained in each iteration, and the next element of the collection.

Since functions in swift are closures, we can pass on the function as a closure as the second argument. We’ll see this in action in an example below.

Besides, due to Swift’s flexibility writing closures, we can see different syntax usages with this function (and others). Take a look at the different uses that are shown in the code examples!

Exploring different uses 🤔

There are other interesting usages for reduce.

For instance, if we have an array of (boolean) conditions, we could reduce them like this:

This opens up interesting possibilities. Imagine we have a struct Person and we have an array of this type. We could use reduce to iterate through all these persons, to know if they’re all adults, for example.

But if you wanted to generate strings of random alphanumeric characters, like passwords, you could use reduce like this:

As stated above, functions are closures, so we could extract the closure to a function, and then pass the function name as parameter to reduce.

Swift 4: Improving performance 🤓

Since Xcode 9.0, Apple added the reduce(into:_:) function, which passes the accumulatingResult by reference instead of value, and since it’s not copying all the elements on every iteration but passing the same object around, it gives a better performance. This is Apple’s recommendation:

This method is preferred over reduce(_:_:) for efficiency when the result is a copy-on-write type, for example an Array or a Dictionary.

So we could use the last example with this function like this:

We can now iterate for example 1000 times, to see the improvement using one method over the other one:

Using reduce(into:_:) 1000 times we can sense a gain of 0.14 seconds.

This is just copying around simple strings. If instead we were copying an array of more complex structs, I guess that the gain would be more significant.

Please feel free to share your thoughts, the article or comments. Any feedback will be appreciated! 😃

--

--

Juan Navas

iOS software engineer @ Qonto. Proud dad of 2 little girls. Avid show consumer. Real Madrid fan.