Simple Higher Order Functions in Swift 3.0 — Map, filter, reduce and flatMap!

In this blog post, I will briefly introduce four very useful and commonly used higher order functions you can use on collection types.

Simply put, higher order functions are functions that you can pass as arguments to other functions. Luckily there are examples below if this is confusing to you.

Map

Loops over a collection and applies the same operation to each element in the collection.

Let’s assume we need to multiply each item by 2 in an array called numberArray. One approach can be:

The For-In Way

In this example above, you made an empty array called emptyArray that holds integer values, looped through the original array, multiplied each element by 2 and appended them to the emptyArray.

Now, let’s use map for a comparison!

Map Example

In these examples above, map accepted a closure (a.k.a a first class function that can be passed around and used in code) as an argument and returned the exact same results as if we used a for loop!

“Wait,” you might say — “Map 1 to 4 look different! Aren’t they all map? Why are they written differently?”

The answer is: YES! They are all the same. It’s just a matter of long-form vs shorthand closure syntax preference.

The Long Form vs the Shorthand Argument Notation

*Please note that when a closure is the only OR last argument of a function, ( ) can be omitted as shown above.

Filter

Loops over a collection and returns an array that contains elements that meet a condition.

Let’s assume we need to filter even numbers only in the following array example. The traditional approach can be:

The Traditional Way

Instead, let’s use filter for the same result:

Filter Example

How simple was that! Filter just eliminated the need of creating an empty array that holds the results, but also takes up valuable computing memory. One line of code — the same exact result!

Reduce

Combines all items in a collection to create a single value.

Let’s assume we need to get the sum of all the numbers in an array of integers. One solution would be to implement another For-In loop:

The Traditional Way

Now let’s use reduce for the same result.

The two parameters in reduce function are a starting value and a function respectively. The function takes a running total and an element of the array as parameters, and returns a new running total.

Reduce Example 1

Again, one line of code — the same result!

Despite the odd syntax, the addition of two adjacent values is taking place between the {} brackets, and the sum is then added to the 0 on the left.

***there is an easier way to write this!***

Reduce Example 2

In the last example, the + operator is substituted for the {$0 + $1} closure, creating an even more simplified and accessible syntax.

Interestingly, the same rule applies to string arrays as well:

Reduce Example 3

FlatMap

When implemented on sequences : Flattens a collection of collections.

Say we have two arrays within an array that we would like to combine into a single array. How would we accomplish this? Probably with another For-In loop:

The Ever-reliable For-In Loop Method

Not this time, flatMap to the rescue!

FlatMap Example 1

Implemented on optionals : Removes nil from the collection.

FlatMap Example 2

Chaining

This is when Higher Order Functions truly shine. You can combine all those HOFs you’ve just learned in one line of code!

Let’s say we want to add the squares of all the even numbers from an array of arrays.

Rather than writing a bunch of for loops and if conditions, we can instead use HOFs to simplify our code and get the same results.

Chaining Example 1

Now, let’s show that the Ints represent money by inserting a $ in front of every element in the arrayInArray example using flatMap and map.

Chaining Example 2

Just one line of code with an awesomely powerful result!

Why Use Higher Order Functions?

These simplistic examples above sum up the reasons why we should use higher order functions in place of more commonly used methods. They help us:

  • Read and understand complex functional programming
  • Write more elegantly and maintainable code that has better readability
  • Improve our Swift language skills

This was just a brief introduction on useful higher order functions for beginners who have just started programming. Functional programming is something that takes a long time to get used to, and understanding and harnessing its power takes a lot of time and practice. So be patient and learn more about it. Read articles, and write functional code as much as you can!

Happy Coding, meow~ 🐱

*Big thanks to Rob Deans for helping out with editing!