Map , Flatmap & CompactMap
Map() vs flatMap() vs CompactMap()
Swift gives us map(), flatMap(), and CompactMap() Collection types. These sound similar but they do completely different things, but the question is When and where to use these methods? So in this article we will see map() vs flatMap() vs compactMap() and compare each of them with examples, we also look at when these are useful and where to use them.
Map()
a function that returns an array with the results of mapping the closure over the collection’s elements
Our collection could be any one of Swift’s collection types, but here we will use an array of integer.
let numbers = [1,2,3,4,5,6,7,8]
let strings = numbers.map{String($0)}
print(strings)
//output: [“1”,”2”,”3”,”4”,”5”,”6”,”7”,”8”]
When to use flatMap
Use this method to receive a single-level collection when your transformation produces a sequence or collection for each element.
Difference between a map and flatMap in the following example:
let studentScores = [“Ram”:[23,45,65,67], “Bibek”:[98,92,54,43]]
let mapScores = studentScores.map{$0.value}
//Output: [[23,45,65,67],[98,92,54,43]] array of array
let flatMapScores = studentScores.flatMap {$0.value}
//Output : [23,45,65,67,98,92,54,43] only array
When to use compactMap
Using this method you receive an array of non optional values when your transformation produces an optional value.
See the differences between normal map and compactMap in below:
let exampleData = [“hello”,”hi”,”how are you”,”10",”12"]
let mapData :[Int?] = exampleData.map{ str in
Int(str)
}
print(mapData)
//Output : [nil, nil, nil, Optional(10), Optional(12)] — there are three nil values “hello”,”hi”,”how are you” they are string data types.
let compactMapData:[Int] = exampleData.compactMap{ str in Int(str)}
print(compactMapData)
//Output : [10,12] — the nil values are filtered out.