High Order Functions in Swift

High Order Functions in Swift

Use the power of HoF to make your code elegant

According to Wikipedia this is the definition of a High Order Function

Source: https://en.wikipedia.org/wiki/Higher-order_function

In Swift High order Functions are generally used on Collections , the most common collection type that you will use with an High order Function is an Array

You can read about the collection protocol in detail using the Apple Developer Documentation

Here are the different High Order Functions that we will learn in this article:

  1. Sorted
  2. Map
  3. Compact Map
  4. Flat Map
  5. Filter
  6. Reduce

Sorted

This function is used to sort the elements of a collection by giving a simple condition. Let’s dive in to the code!

This is a simple use case of sorted where we used an array of Integers and sorted them in ascending order. If you wish to sort them in descending order or by using some other conditions then you can use the closure format to give the specific condition. Let’s take a new array and sort it in descending order using the closure syntax.

If you know about closures in depth then you would remember that we can use a short hand syntax as Swift has Type Inference which means that closure arguments can infer their type from the collection on which they are being used. Let’s use the short hand method to do the same sorting operation.

Map

Map takes each element of a collection and does some work on it and return a new collection. We can use Map to square the elements of array or may be add/multiply each element by a number. Let’s see how we can use map.

If you look at the closure we have an argument which is a number and then we are calculating the square of that number and returning it.

This is how we multiply each element of an array with a new number:

We can also use Map to convert String values to Int values.

Compact Map

Compact map is similar to Map with only one major difference. Map does not accommodate the use of Optionals whereas Compact Map does. In the above example of converting String to Int the map function worked because all the string values can be type casted to integers without any failure. If there is any string value which cannot be converted than Compact Map will skip that particular value. Let’s see this in action

In the above example This will fail and This will also fail cannot be converted to Int so compactMap will ignore them and return rest of the values in an Array

Flat Map

Flat map is used to convert a multi-dimensional array in to one dimension array. We will use flatMap to convert a two dimensional array in to one dimensional array.

Filter

Filter as the number suggests can be used to filter out the elements of a Collection by applying some condition to each and every element. We can use filter to get an array which contains integers greater than a particular value or if we have an array of names we can filter out the names by giving a condition such as names starting with S or names containing S . Let’s see all of these examples in action

In this example we are using an array of integers and checking if the number is greater than 50 or not. If the number is greater than 50 the closure returns True and that element is appended to the returning array and in case the result is False that number will not be included.

In the above example we are using a string method called hasPrefix which checks whether the first character is the passed character or not and than returns a boolean value.

Reduce

If we use reduce on an Array it will return the result by combining each element of the array itself. Let’s take an example to understand this better. If we have an array of number and we want to get the sum of all the numbers we would use reduce . It will iterate over each element and add them together and return the result.

reduce takes two different arguments:

  1. Initial Result
  2. Next Partial Result closure with two arguments (partialResult, Element)

Let’s use reduce to calculate the sum of all the elements of an Array.

In the first pass partialSum = 0 and number = 2

In the second pass partialSum = 2 and number = 4

In the third pass partialSum = 6 and number = 6

This will it will go on till pass 5 and the returned result will 30 which is equal to sum of all the elements of the Array.

Wrapping Up

This is all about the most common High Order Functions in Swift. Apple highly recommends the use of High order Functions in your code as their internal implementation is fully tested and it also makes it easier for fellow developers to read your code.

Feel free to drop a comment if you have anything to discuss.

Did you find this article valuable?

Support Everything Swift by becoming a sponsor. Any amount is appreciated!