Higher order functions in Swift: Filter, Map, Reduce, flatmap, compactMap

Ever since I learned about functions and closures in detail, I wanted to know more about the advantages and usages of these in programming. I read about higher order functions that can be used on collection types and this is what I understood.

I don’t know who that is over there at the top.

Pass function to another function:

higher order functions in swift

Return function from another function:

You should understand what a closure is before going through the following. Read my article on closures

Map

Map on array:

let arrayOfInt = [2,3,4,5,4,7,2]
var newArr: [Int] = []for value in arrayOfInt { newArr.append(value*10) }print(newArr) // prints [20, 30, 40, 50, 40, 70, 20]
maps on int array
let newArrUsingMap = arrayOfInt.map { $0 * 10 }
simplifying the map closure syntax

Map on Dictionary:

let bookAmount = [“harrypotter”:100.0, “junglebook”:100.0]
map on dictionary
map on dictionary return values

Map on set:

What if you want to know the index of the collection while applying map to it??

let numbers = [1, 2, 4, 5]let indexAndNum = numbers.enumerated().map { (index,element) inreturn "\(index):\(element)"
}
print(indexAndNum) // [“0:1”, “1:2”, “2:4”, “3:5”]

Filter

Filter on array

filter using for-in loop
filter an int array
Simplified filter closure on Int array

Filter on dictionary

let bookAmount = [“harrypotter”:100.0, “junglebook”:1000.0]
filter autocomplete on dictionary
let filteredArrayOnDict = bookAmount.filter { $1 > 100}

Filter on set

filter on set

Reduce

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

Reduce on arrays

reduce method on arrays
let reducedNumberSum = numbers.reduce(0) { $0 + $1 }print(reducedNumberSum) // prints 10
reducing on int array
let reducedNumberSum = numbers.reduce(0,+) // returns 10
let reducedNumberSum = numbers.reduce(0) { $0 * $1 }
// reducedNumberSum is 0...
let reducedNumberSum = numbers.reduce(0,*)
let codes = ["abc","def","ghi"]let text = codes.reduce("") { $0 + $1} //the result is "abcdefghi"orlet text = codes.reduce("",+) //the result is "abcdefghi"

Reduce on dictionary

let bookAmount = [“harrypotter”:100.0, “junglebook”:1000.0]
reducing dictionary
let reducedBookNamesOnDict = bookAmount.reduce(“Books are “) { $0 + $1.key + “” } //or $0 + $1.0 + “”

Reduce on set

Flatmap

Read it like : map + (Flat the collection)
(fig — 1) Read the above definition and have a look at this code.
(fig — 2)… and this (string is a collection from swift 4).
[“abc”,”def”,”ghi”].map { $0.uppercased() }
output: [“ABC”, “DEF”, “GHI”]
output: ["A", "B", "C", "D", "E", "F", "G", "H", "I"]
Finally, this is what flatMap does to a string

Tip:

I think, now it is clear what a flatMap does.

Flatmap on array

flatmap of array of array of int

Flatmap on array of dictionaries

flatmap an array of dictionaries

Flatmap on set

flatmap on set

Advantages of flatmap:

Removing optionals:

flatmap to remove optionals.

Flatmap by filtering or mapping

filtering while flatmap
let onlyEven = collections.flatMap { $0.filter { $0 % 2 == 0 } }

Chaining : (map + filter + reduce)

You can read my article on chaining methods to understand its working.

add the squares of all the even numbers from an array of arrays.

CompactMap

compactmap on dictionary

Tip:

Conclusion

If you enjoyed reading this post, please share and give some clapps so others can find it 👏👏👏👏👏 !!!!

iOS and tvOS developer, dreamer, photographer 🤨