Photo by Fabian Grohs on Unsplash

Swift 4 ~~ The Higher order Functions — Filter , Map , Reduce and Sorted

ANANTHA KRISHNAN K G
Swift Dynamics
Published in
4 min readOct 3, 2018

--

You might have heard about Higher order functions in Swift. In simple terms higher order functions are developer friendly code snippets which do complex computations in few lines.

In swift we have Filter(), Map(), Reduce() and Sorted() HOFs . All of these have its own benefits and simple to use in our code. Let me show you how to use them with some interesting examples in Swift4.

1. filter(_:)

Filter method will check a condition and and if the condition satisfies it will return an object back. You can use the filter(_:) with String , Array , Dictionary , Set etc.

Let’s see on Set how it can be used. I have set of names and I need to pick names which have only 5 characters . So how I do it ?

// Set of Names
let nameSet: Set = ["trivan", "mary", "larns", "tria"]
// Result Set
var resultSet: Set<String> = []
// iterate throgh each element in nameSet
nameSet.forEach { (element) in
if element.count == 5 {
resultSet.insert(element)
}
}
print(resultSet)

How this can be done using the HOF filter (_:) ? Let me show you the code for above requirement with the filter (_:)


let nameSet: Set = ["trivan", "mary", "larns", "tria"]
//Inline Implementation
let resultNames = nameSet.filter { $0.count == 5 }
// Full Implementation
let resultNames = nameSet.filter { (value) -> Bool in
return value.count == 5
}
print(resultNames)

Easy right ?. here the `$0` represents each elements inside the Set.

Let’s see filter(_:) in a String,

let myString = "Ananth"// Inline 
let myNumbers = myString.filter { "Ananth Krishnan".contains($0) }
// Full implementation
let myNumbers = myString.filter { (a) -> Bool in
return "Ananth Krishnan".contains(a)
}
print(myNumbers)

Now in the Dictionary ,

let myDictionary = ["Ananth":26, "Roy": 27, "Laila":23, "Louise":28,"Nova":25]//Inline Implementation
let resultDic = myDictionary.filter{$1 < 25}
// Detailed implementation
let resultDic = myDictionary.filter { (name,age) -> Bool in

return age < 25
}
print(resultDic)

here ` $1` is the second element, which in this case the age. if you want the name the variable will be `$0` . Okay that’s it for Filter(_:).

2. map(_:)

Map(_:) will help you to update/edit each element in the array or dictionary you have . Instead of looping through each object in a for loop simply use the map(_:).

let’s see how we can use it in the a string array ,

var nameArray =  ["trivan", "mary", "larns", "tria"]//Inline - replace occurrences of `a` with `ii`
let resultNames = nameArray.map{$0.replacingOccurrences(of: "a", with: "ii")}
// Detailed implementation
let resultNames = nameArray.map { (element) -> String in
return element.replacingOccurrences(of: "a", with: "ii")
}
print(resultNames)

Let’s see how the map works in a Dictionary ,

let myDictionary = ["Ananth":26, "Roy": 27, "Laila":23, "Louise":28,"Nova":25]//Inline
let tupleArray = myDictionary.map{ ($0,$1*2)}
// Detailed func
let tupleArray = myDictionary.map { (key: String, value: Int) in
return (key, value * 2)
}
myDictionary = Dictionary(uniqueKeysWithValues: tupleArray)

print(myDictionary)

There is one more map function called - `compactMap(_:)`. If the input contains any nil/optional values CompactMap(_:) will handle the optional values gracefully. Let me show you an example ,

let nameArray:[String?] =  ["trivan", nil,"mary", "larns", "tria"]


let filteredNilArray = nameArray.compactMap{$0?.replacingOccurrences(of: "a", with: "A")}
print(filteredNilArray)

3. Reduce(_:)

Reduce returns the result of combining the elements of the sequence using the given closure. There are two values inside the reduce(_:) function. One is the initial result, which will be the starting value for the reduce function. If there is no result to return we will get this initial value in return. The other value is the partial result, which is an accumulating value that passed to the next sequence or to the end result. Let’s dive into the examples,

In array we can use reduce for , calculating the sum, difference or any mathematical calculations, finding the largest/smallest string , character count etc.

let nameArray:[String?] =  ["trivan","mary", "larns", "tria"]// print the largest string
let nameReduce = nameArray.reduce("",{$0!.count > $1!.count ? $0 : $1 })
print(nameReduce)

In a dictionary we can use the Reduce(_:) as follows,

let nameDic = ["Ananth":29, "Roy": 27, "Laila":23, "Louise":28,"Nova":25]// Inline Return name with largest number value(age)
let name = nameDic.reduce((key:"",value:0), {
return $0.value > $1.value ? $0 : $1
})
// Another way
let name = nameDic.reduce((key:"",value:0)) { (res, arg1) in

return res.value > arg1.value ? res : arg1
}
name1print(name)

4. Sorted(_:)

Sorted(_:) can be used to rearrange the values. We can use it in String, Array, Dictionary etc.. Let’s see the examples.

Let’s add sorted(_:) for an ar

var numberArr = [4,6,3,1,6,8,9,0,4]var newArr = numberArr.sorted(by: {$0 > $1})newArr = numberArr.sorted(by: >)newArr = numberArr.sorted(by: <)newArr = numberArr.sorted{$0 < $1}newArr = numberArr.sorted { (a, b ) -> Bool in
return a < b
}
print(newArr)

Let’s try it on a String ,

var stringValue = "Ananth"
var stringV = stringValue.sorted()
String(stringV)

stringV = stringValue.sorted(by:<)

String(stringV)

stringV = stringValue.sorted(by:>)

String(stringV)

stringV = stringValue.sorted{$0 > $1}

String(stringV)

Now on a Dictionary,

let nameDic24 = ["Ananth":29, "Roy": 40, "Laila":23, "Louise":28,"Nova":25]// Sort by values(ages)
let sortedKeysAndValues = nameDic24.sorted{ $0.1 < $1.1 }
print(sortedKeysAndValues)

Conclusion

Higher order functions are easy to understand if you are aware of closures and functional programming . You can find the examples here in Github . Hope you have enjoyed reading about Higher order functions . Don’t forget , your claps matters 🤪 . Happy Coding !! 💪 🖥

--

--