In previous articles we had seen how to improve the architecture of our code through design patterns and the use of SOLID principles. Now we will see how to improve the Swift code with higher order functions. Surely you have used them more than once, but what are they and how do 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 or 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 that 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 the uppercase letters. We could do this with a for…in loop:

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

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

In the example we are seeing we apply it as follows:

What map 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 map 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.

The compactMap function returns an array containing the non-nil results after applying the given transformation to each element of a sequence.

Therefore, in the example we are 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 is not optional).

flatMap

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

For example, let’s first look at how we would 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 from 1 to 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 have indicated in the function) and the value of y is 1. So the result 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 have not used the contains function since, as we will see later, it is also a higher order function.

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

But it does not 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 have 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 that we want to order in some way to show them. For example, in the word array examples seen so far, those words are not 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

It performs a function similar to for…in, but unlike this, 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 have just seen some of the most commonly used higher order functions and their power using some examples. These functions allow, on the one hand, to reduce the amount of code and, on the other, to make it clearer and more concise.

Categories: Swift

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Follow on Feedly
shares