Higher Order Functions in Swift

Pushpendra Singh
2 min readOct 30, 2020

A higher order functions is a function that takes a or more closures as an argument, or returns a closure. Higher order function is in contrast to first order functions, which don’t take a function as an argument or return a function as output.

Here are some swift higher-order functions — map, CompactMap, flatMap, filter, reduce, sort, and sorted.

Using Abb. higher order functions → HOF

There are a few benefits to understanding HOF.

Understand functional programming

Brevity, more concise, less code which we all love

More readable and easy to use code

It can be used for all data structures while in this tutorial we will just focus on Array or Sequence.

Lets do one exercise here. Open your playground

Read the definition and try to write a function.

Photo by Zan on Unsplash
func function(_ anotherFunction: () -> Void) {    print("--- \(function) started ---")    anotherFunction()    print("--- \(function) ended ---")}function {    print("Closure Executed")}

Can you guess the output?

This is how the output look like

--- (Function) started --- Closure Executed --- (Function) ended ---

I believe till now, you can frame how you can write down the definition of the once we use on day to day basis. So lets jump on writing the definition of map.

Map

Map is simply apply operation to every element of Array/Sequence and provides an array of tansformed values

[1, 2, nil, 3] → [1, 2, 3]

More generic definition would be “Transformed values collection from sequence of values collection”

extension Sequence {typealias C= Elementfunc myMap<D>(_ transformClosure: (C) -> D) -> [D] {var result = [D]()forEach { element inresult.append(transformClosure(element)) // append tansformed value}return result}}

Compact Map

It is simply droping element which cannot be mapped

extension Sequence {typealias C= Elementfunc myCompactMap<D>(_ transformClosure: (C) -> D?) -> [D] {var result = [D]()forEach { element inif let transformedValue = transformClosure(element) {result.append(transformedValue)}}return result}}

Now Flatmap, Filter, Sort and Reduce is left. please try to do them as part of assignment and paste it in comments. If you face any difficulty do comment below.

If you like this content please dont forget to 👏 and paste your assignment in comments so that I will be aware that you finished this exercise properly.

--

--