Higher-Order Functions in Swift

Introduce ‘map’, ‘reduce’, ‘filter’, ‘flatMap’, and ‘compactMap’ into your code

Raúl Ferrer
Better Programming
Published in
5 min readJun 9, 2020

--

Photo by Avel Chuklanov on Unsplash
Like my content? What about a coffee.

In previous articles, we’ve seen how to improve the architecture of our code through design patterns and the use of SOLID principles. Now we’ll see how to improve our Swift code with higher-order functions. Surely, you’ve used them more than once, but what are they and how can you improve your Swift code with higher-order functions?

Swift Higher-Order Functions

Higher-order functions are functions that take other functions or closures as arguments and that return a function or a closure. These functions are used with arrays, sets, and dictionaries and act on the elements they contain (this is done by methods that are applied to the elements of the collection using the point syntax).

Some of the best-known functions are map, compactMap, flatMap, reduce, filter, contains, sorted, forEach, and removeAll.

‘map’

The map function works by performing an operation on all the elements of a collection and returning a new collection with the results of that operation.

For example, let’s suppose we have an array with several words with all their letters in lowercase, and we want to obtain a new array with each of these words but with all uppercase letters. We could do this with a forin loop:

Let’s see how to do it with the map function. As shown in the Apple documentation, it’s declared as:

transform accepts an element from a collection or a sequence as a parameter and returns a transformed value of the same type or a different one.

In the example, we’re seeing we apply it as follows:

What it does is loop through the entire array of elements, apply the uppercased() method on each of them, and return a new array with these values.

Anyway, we can reduce this expression by using the shorthand argument $0, which refers to any elements of the array:

‘compactMap’

Now suppose that inside the array of the previous example there are nil values. If we use the function, we must take into account whether the value to be acted on is nil or not:

But what if what we really want is to get the new array but without the nil values? To achieve this we have the compactMap function.

Therefore, in the example, we’re seeing:

In other words, compactMap loops through all the elements of the array and applies the method to non-nil values, returning them in an array, in this case of type String (that is, the value of String isn’t optional).

‘flatMap’

The flatMap function allows us to transform a set of arrays into a single set that contains all of the elements. As Apple declares in its documentation:

For example, let’s first look at how we’d do it without flatMap:

But with flatMap, we can simplify the code as follows:

‘reduce’

reduce is a function that, when applied to a collection, returns the result of combining the elements of that collection:

For example, if we have an array with the numbers 1-10 and we want to obtain their sum, we can do it in the following way without using the reduce function:

With reduce, we simply do the following:

In the first iteration, the value of x is 0 (as we’ve indicated in the function), and the value of y is 1. So the result of x + y will be 1. In the second iteration, x is 1, and y is 2. So the result will be 3. And so on.

In a more simplified way, we can write:

‘filter’

As its name suggests, the filter function filters the content of a collection and returns a new collection that contains the elements that meet a certain condition:

For example, suppose we have the word collection from the first examples and we want to get a new collection of words containing the letter o. Without the filter function, we could do it in the following way:

In this case, we haven’t used the contains function since, as we’ll see later, it’s also a higher-order function.

Now we’re going to simplify this code using the filter function:

But it doesn’t have to apply a single condition; we can apply several conditions. For example, in the previous case, we can make it return the words that contain the vowel o and whose length is 5 characters or more:

‘contains’

In the previous example, we’ve used the contains function to determine if a word contained the vowel o. Well, contains is a higher-order function that allows you to check if there are elements that meet a certain condition and return true or false depending on whether or not they meet it.

As Apple indicates in its documentation, contains returns a boolean value that indicates whether the sequence contains the given element.

‘sorted’

On numerous occasions, we find a collection of elements we want to order in some way to show them. For example, in the word-array examples seen so far, those words aren’t arranged alphabetically.

But what if we wanted to order them alphabetically? We could use some algorithm, like:

We could reduce this code using the swapAt method, which allows us to exchange the positions of two elements in a sequence:

To further reduce this code, we can use the sorted function. This function returns the elements of a sequence ordered in ascending order (as long as the elements of the collection adopt the Comparable protocol):

On the other hand, if we want to use our own condition to order the collection, we use the function sorted(by:), which, as Apple indicates in its documentation, returns the elements of the sequence, ordered using the predicate given as the comparison between elements.

For example, if we want the words to be ordered in reverse-alphabetical order, we can do the following:

In this case, by indicating the symbol >, we order the collection in descending order.

‘forEach’

Neither continue nor break can be used inside forEach, just return:

‘removeAll’

The higher-order function removeAll(where:) allows us to remove elements from a sequence that meet certain conditions:

For example, if we want to remove all the even numbers from a sequence, we can do the following using removeAll:

The power of removeAll(where:) is seen more clearly in the example that Apple shows in its documentation, where it uses it to remove the vowels of a phrase:

Function Concatenation

The first-order functions can be applied consecutively, concatenated. For example, we can take an array containing arrays of numbers and calculate their sum:

First we apply the flatMap function to obtain an array with all the numbers. Then we apply the reduce function to add them.

Conclusion

We’ve just seen some of the most commonly used higher-order functions and their power by using some examples. These functions allow us, on the one hand, to reduce the amount of code and, on the other, to make our code clearer and more concise.

--

--

Mobile Engineering Manager & Mobile Developer | Author & Content Creator | I help you become a better developer