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:
- func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
Using For-loop
- var arrayOfInt = [2,4,6,8]
- var numbers: [Int] = Array()
- for number in arrayOfInt {
- numbers.append(number*number)
- }
- Output : [4, 16, 36, 64]
Using Map
Example - 1
- var arrayOfInt = [2,4,6,8]
- let numbersArray = arrayOfInt.map({$0*$0})
- print(numbersArray)
- Output : [4, 16, 36, 64]
Example - 2
- let cast = ["Pravesh", "Pankaj", "Ayush", "Manish"]
- let lowercaseNames = cast.map { $0.lowercased() }
- print(lowercaseNames)
-
- Output : ["pravesh", "pankaj", "ayush", "manish"]
-
- let cast = ["nitin", "gaurav", "sourabh", "amit"]
- let upperCaseNames = cast.map { $0.uppercased()}
- print(upperCaseNames)
-
- 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:
- func flatMap<SegmentOfResult>(_ transform: (Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence
Example
- let arrayOfInts = [2,nil,8,nil,17,nil,98]
- let flattenArray = arrayOfInts.flatMap({$0})
- print(flattenArray)
- Output : [2, 8, 17, 98]
Note
FlatMap flattens the collection of collections.
Example
- let scoresByName = ["Pravesh": [0, 5, 8], "Ayush": [2, 5, 8]]
- let flatMapped = scoresByName.flatMap{ $0.value }
-
- print(flatMapped)
- 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:
- func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Self.Element) throws -> Result) rethrows -> Result
Example - Reduce on Array
- let numbers = [1, 2, 3, 4]
- let numberSum = numbers.reduce(0, { x, y in
- x + y
- })
-
We can also use this in this way.
- var arrayOfInt = [2,4,6,8]
- let numberSub = arrayOfInt.reduce(0,+)
- print(numberSub)
When numbers.reduce(_:_:) is called, the following steps occur.
- The nextPartialResult closure is called with initialResult is zero, In this case - the first element of numbers, returning the sum 1.
- The closure is called again repeatedly with the previous call's return value and each element of the list.
- 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.