Map, FlatMap And Reduce In Swift

In this article, I will explain the concept of Map, FlatMap/CompactMap, Reduce, and Filter in Swift.

Introduction 

 
In Swift, you can use Map, FlatMap, and Reduce to loop through collection types such as an Array and a Dictionary without using a For loop. Map, FlatMap, and Reduce are higher-order functions in Swift programming.
 

Map

 
Using Map, you can loop through a collection. The Map function returns an array containing the results of applying to map in each item of a collection.
 
Declaration
 
Declared as following:
  1. func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]  
Using For-loop 
  1. var arrayOfInt = [2,4,6,8]  
  2. var numbers: [Int] = Array()  
  3. for number in arrayOfInt {  
  4.     numbers.append(number*number)  
  5. }   
  6. Output : [4, 16, 36, 64]  
Using Map
 
Example - 1  
  1. var arrayOfInt = [2,4,6,8]  
  2. let numbersArray = arrayOfInt.map({$0*$0})  
  3. print(numbersArray)  
  4. Output : [4, 16, 36, 64]  
Example - 2
  1. let cast = ["Pravesh""Pankaj""Ayush""Manish"]  
  2. let lowercaseNames = cast.map { $0.lowercased() }  
  3. print(lowercaseNames)  
  4.   
  5. Output : ["pravesh""pankaj""ayush""manish"]  
  6.   
  7. let cast = ["nitin""gaurav""sourabh""amit"]  
  8. let upperCaseNames = cast.map { $0.uppercased()}  
  9. print(upperCaseNames)  
  10.   
  11. Output : ["NITIN""GAURAV""SOURABH""AMIT"]  

FlatMap 

 
The flatMap(_:) is similar to Map function except for the functionality that this will remove all the nil values from a collection.
 
Declaration
 
Declared as following:
  1. func flatMap<SegmentOfResult>(_ transform: (Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence 
Example
  1. let arrayOfInts = [2,nil,8,nil,17,nil,98]  
  2. let flattenArray = arrayOfInts.flatMap({$0})  
  3. print(flattenArray)  
  4. Output : [2, 8, 17, 98]  
Note
FlatMap flattens the collection of collections.
 
Example
  1. let scoresByName = ["Pravesh": [0, 5, 8], "Ayush": [2, 5, 8]]  
  2. let flatMapped = scoresByName.flatMap{ $0.value }  
  3. // [0, 5, 8, 2, 5, 8] - flattened to only one array  
  4. print(flatMapped)  
  5. Output : [0, 5, 8, 2, 5, 8]  

Reduce

 
Reduce returns the result of combining the elements of the sequence using the given closure. 
 
Declaration
 
Declared as following:
  1. func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Self.Element) throws -> Result) rethrows -> Result  
Example -  Reduce on Array 
  1. let numbers = [1, 2, 3, 4]  
  2. let numberSum = numbers.reduce(0, { x, y in  
  3.     x + y  
  4. })  
  5. // numberSum == 10  
We can also use this in this way.
  1. var arrayOfInt = [2,4,6,8]  
  2. let numberSub = arrayOfInt.reduce(0,+)  
  3. print(numberSub)  
When numbers.reduce(_:_:) is called, the following steps occur.
  1. The nextPartialResult closure is called with initialResult is zero, In this case - 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 list.
  3. When the list exhausted, the last value returned from the closure is returned to the caller.

Summary

 
That's it. I hope you have now understood how to declare and use Map, FlatMap/CompactMap, and Reduce in Swift programming.