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:

Image for post
Image for post

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!

Image for post
Image for post

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.

Image for post
Image for post

*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:

Image for post
Image for post

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

Image for post
Image for post

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:

Image for post
Image for post

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.

Image for post
Image for post

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!***

Image for post
Image for post

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:

Image for post
Image for post

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:

Image for post
Image for post

Not this time, flatMap to the rescue!

Image for post
Image for post

Implemented on optionals : Removes nil from the collection.

Image for post
Image for post

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.

Image for post
Image for post

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.

Image for post
Image for post

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!

Written by

I’m Luna, a.k.a Mimicat who loves to create, collaborate, and of course, code ❤ Meow~ // iOS Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store