High-Order Functions

Sejan Miah
killingMeSwiftly
Published in
3 min readAug 27, 2017

What is a high order function?

A function that takes in a function as an argument, returns a function, or both. Yes, functions can take in other functions, they are closures. A closure is a self-contained block of code that can be passed around. Functions are considered 1st Class Citizens, meaning Swift supports to pass functions as arguments, return functions and also assign them to variables. This is possible because a function is a kind of closure.

MAP:

The MAP method, takes in a closure as an argument and the closure calls each item once in the array. After these items are called, we receive back an array containing the mapped results over the sequence’s elements.

Let’s take a look at some examples:

In the variable newNumbers, the map method goes through each element in the array, while satisfying it’s condition, which is to multiple each element in the array by itself. The variables newNumbers and mappedNumbers showcase the different ways in which we can write the closure implementation. $0 is shorthand notation for the first element in the closure, $1 is the second one. If we look at the second line, we can see that it is more verbose, but does the same thing. We get an array of [1, 4, 9] in both instances.

Now let’s create a function that does the exact same thing and pass it into map:

If we look at the our fettyMap constant, we are getting back an array of squared integers and we were able to do this by passing in our square function as a parameter into map! It is important to note that the return type of a mapped function does NOT have to be the same TYPE as the function’s elements, this is depicted through our constant fettyMap2. High-Order functions are dope!

Here are a few examples of using the map function but with arrays of strings:

Finally, I will leave you with an example of chaining High-Order Functions.

I hope that after these few examples you’ll try out these wonderful methods.

--

--