Higher Order Functions in Swift

Batikan Sosun
3 min readNov 22, 2020

Make some work easier by higher-order functions.

Photo by Ben Kolde on Unsplash

I share programming guides that make programmer’s practices simple.

In this guide, I’m going to explain Swift’s higher-order functions with examples as much as I can.

Sometimes it’s hard to understand what you’re doing with these. So I will explain in general terms and then give a few examples.

In mathematics and computer science, a higher-order function is a function that does at least one of the following: takes one or more functions as arguments (i.e. procedural parameters), returns a function as its result. — Wikipedia

Another definition in swift terms (like a closure):

Swift’s Higher-order functions are functions that take other functions or closures as arguments and that return a function or a closure.

Let’s list some of these functions.

  1. map
  2. compactMap
  3. flatMap
  4. reduce
  5. filter

All of these functions are used with collection types(arrays, sets, and dictionaries) and take action on the elements they contain.

Let’s examine them in-depth step by step.

map

Let’s begin with the first, and likely the most famous higher-order function called map.

In short, map performs an operation on all the items of a collection and returns a new collection with the outcomes of the operation on the original items.

If we had a collection and we needed to capitalize each item of that collection, we would follow the below procedure.

The solution in the traditional way:

In the Apple documentation, it’s declared as:

func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]

The loop applies the uppercased() method on each of them, and return a new array with these values.

Reduce the expression by the $0 reference.

compactMap

Sometimes the collections contain optional types. In the previous example, if it contains optional values you need to nullable-check before the transform.

The solution in the traditional way:

In the Apple documentation, it’s declared as:

func compactMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]

Following the above way will make it easier to solve the problem.

flatMap

flatMap performs an operation that combines multiple arrays into one array, and returns a new array as a result.

The solution in the traditional way:

In the Apple documentation, it’s declared as:

func flatMap<SegmentOfResult>(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence

Brilliant solution:

reduce

In a collection, the purpose of the reduce function is to generate a single value by summing its values.

The solution in the traditional way:

In the Apple documentation, it’s declared as:

func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result

Parameters

initialResult

The value to use as the initial accumulating value. initialResult is passed to nextPartialResult the first time the closure is executed.

nextPartialResult

A closure that combines an accumulating value and an element of the sequence into a new accumulating value, to be used in the next call of the nextPartialResult closure or returned to the caller.

short usage:

When numbers.reduce(_:_:) is called, the following steps occur:

  1. The nextPartialResult closure is called with initialResult0 in this case—and the first element of numbers, returning the sum: 1.
  2. The closure is called again repeatedly with the previous call’s return value and each element of the sequence.
  3. When the sequence is exhausted, the last value returned from the closure is returned to the caller.

If the sequence has no elements, nextPartialResult is never executed and initialResult is the result of the call to reduce(_:_:).

Complexity: O(n), where n is the length of the sequence. — Apple documentation,

filter

The filter function’s purpose is to filter the items of a collection and returns a new collection that contains the items that meet a specific condition.

For example, filter the words which have the first letter is “c”.

The solution in the traditional way:

In the Apple documentation, it’s declared as:

short usage:

Final Words

I have tried to explain the most commonly used higher-order function and explained it with examples. The reference $0 always provides a handy way to get a clearer and more readable code. These functions provide us, to reduce the amount of code and, to make our code clearer and more comprehensive.

If you have any criticism, question, or suggestion, feel free to post them in the comment section below!

Thanks for reading.

P.S.: and if you like my article, don’t forget to clap 👏

Follow me on Twitter and Linkedin

--

--

Batikan Sosun

Tweeting tips and tricks about #swift #xcode #apple Twitter @batikansosun Weekly Swift Blogging