Higher Order functions in swift

Lakshmi K
4 min readMay 6, 2022

--

Higher order functions are applied to arrays, dictionaries and sets in swift. In simple way we use higher order functions in place of writing so many for loops to loop through arrays, dictionaries and sets.

Higher order functions

List of higher order functions:

  1. Map
  2. CompactMap
  3. FlatMap
  4. Reduce
  5. Filter
  6. Contains
  7. Sorted
  8. ForEach
  9. removeAll

Map:

It will loop through each and every element in collection , then perform operations provided by us and returns new collection.

First let’s see how we can multiply an array of elements with provided multiplier

for loop ex:

let numbArray : [Int] = [1,2,3,4,5,6,7,8,9,10]

let multiplyNumber : Int = 2

var multipliedArray : [Int] = [Int]()

for eachNumb in numbArray {

multipliedArray.append(eachNumb * multiplyNumber)

}

print(multipliedArray) //result: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

For a single array this may look fine , but what if we got complex collections and need to perform operations on it.

Let’s see how to implement the above example using map higher order function

Ex:

let newArray = numbArray.map { eachNum in

return eachNum * multiplyNumber

}

print(newArray) //result: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

We can write the above code in much simpler way

let newShortArray = numbArray.map{$0 * multiplyNumber}

print(newShortArray) // result: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Here $0 is nothing but each element in that collection.

CompactMap:

In map function we may get nil values, sometimes we need to check if the value is nil or not. While compactMap will return only valid values without nil values. Let’s see with an example

With Map:

let optionalNumbArray : [String] = [“1”,”2",”3",”four”,”5",”six”,”7"]

let newMapArray = optionalNumbArray.map { eachNum -> Int? in

if Int(eachNum) != nil {

return Int(eachNum)

}

else {

return nil

}

}

print(newMapArray) // result: [Optional(1), Optional(2), Optional(3), nil, Optional(5), nil, Optional(7)]

With CompactMap:

let newCompactArray = optionalNumbArray_1.compactMap { Int($0) }

print(newCompactArray) // result: [1, 2, 3, 5, 7]

with compactMap functions we avoided nil values in the result

FlatMap:

When we have multidimensional collections and wants to merge them as one then we can use flatmap

Ex:

var multiDimensionalArray : [[Int]] = [[1,2,3], [4,5,6],[7,8,9]]

var singleArray = multiDimensionalArray.flatMap{ $0 }

print(singleArray) // result: [1, 2, 3, 4, 5, 6, 7, 8, 9]

If we have 2 single arrays and wants to merge them as multi dimensional array , then also we can use map and flatmap combined

Ex:

let firstArray = [1, 2, 3]

let secondArray = [4, 5, 6]

let resultArray = firstArray.map { first in secondArray.map {second in (first, second)}}.flatMap{$0}

print(resultArray) // result: [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

Reduce:

reduce function takes a collection and converts it into a single value.

Ex:

var sumArrayElements : [Int] = [1,2,3,4,5,6,7,8,9,10]

var sumValue = sumArrayElements.reduce(0) { firstValue, secondValue in

return firstValue + secondValue

}

print(sumValue) // result: 55

It always takes 2 values , first value is the result of the previous operation provided in the closure. Second values is the each value from the collection. After reduce , we have braces with value 0 like reduce(0) , 0 is the initial/first value in the closure, change 0 value to another value and see the results , then we can clearly understand what is initial value.

we can write above function in short way

var anotherSumValue = sumArrayElements.reduce(5) { $0 + $1 }

print(anotherSumValue) // result: 60

Filter:

To apply filters in the collection , we use filter function.

Ex:

var agesOfvotersApplied : [Int] = [24,17,45,23,34,26,47,29]

var approvedVotersAge = agesOfvotersApplied.filter{ $0 > 18}

print(approvedVotersAge) // result: [24, 45, 23, 34, 26, 47, 29]

var govtAprovedAges = agesOfvotersApplied.filter{ $0 > 18 && $0 < 35 } // multiple conditions

print(govtAprovedAges) // result: [24, 23, 34, 26, 29]

Contains:

To check if the collection elements contains provided value we use Contains

Ex:

var countryNames : [String] = [“India” , “USA”, “China” , “Australia”,”UK”]

var iCoutnryName = countryNames.filter{ $0.contains(“i”)}

print(iCoutnryName) // result: [“India”, “China”, “Australia”]

Sorted:

To sort elements either in ascending or descending order we use sorted function

Ex:

var agesOfvotersApplied : [Int] = [24,17,45,23,34,26,47,29]

var anotherSortArray = agesOfvotersApplied.sorted() // default sort is ascending order

// we can also write in this way

var mySorterArray = agesOfvotersApplied.sorted{ $0 < $1 } // result : [17, 23, 24, 26, 29, 34, 45, 47]

// another way to write , which is simpler way is

var descSortArray = agesOfvotersApplied.sorted(by: >) // result: [47, 45, 34, 29, 26, 24, 23, 17]

ForEach:

for each works like for loop in swift, only difference is we can’t use continue or break inside for loop , so it will make sure we go through each and every element of collection

Ex:

var countryNames : [String] = [“India” , “USA”, “China” , “Australia”,”UK”]

countryNames.forEach {

print($0.uppercased())

}

RemoveAll:

If we want to remove some occurrence of any sub string from a string or any element from collection which matches the condition then we can use removeAll

Ex:

Collection Ex:

var sumArrayElements : [Int] = [1,2,3,4,5,6,7,8,9,10]

sumArrayElements.removeAll(where: {$0 % 3 == 0})

print(sumArrayElements) // [1, 2, 4, 5, 7, 8, 10]

String Ex:

var myStatement = “hello \\welcome to \n\\ios learning\\ \n\n\n”

let additionalChar : Set<Character> = [“\\” , “\n”]

myStatement.removeAll(where: { additionalChar.contains($0) })

print(myStatement) // result: hello welcome to ios learning

We have one advantage, we can also use multiple higher order functions on single collection

Ex:

var multiDimensionalArray : [[Int]] = [[1,2,3], [4,5,6],[7,8,9]]

var singleArraysum = multiDimensionalArray.flatMap{ $0 }.reduce(0) { $0 + $1

}

print(singleArraysum)// result : 45

Conclusion: We use higher order functions to make code easier, to avoid writing multiple lines of code.

Please go through my other articles , thanks for reading. Happy Coding and Reading :).

https://medium.com/@kn.lakshmi948/what-are-the-access-controllers-in-swift-80d5530cf3ba

--

--