Higher order FUNctions in Swift
map vs. flatMap
Did you ever wonder about the difference between map
& flatMap
? Well, in this post I want to show you some use cases on when to call which function. It’s actually pretty easy to understand. 😊
The example
In my example we declared the following two types:
Nothing new so far and pretty lame code. Now let’s continue with the fun part:
Challenge #01
Retrieve an array containing all
firstNames
from thepeople
array.
This one is actually pretty easy. We just have to call map
on people
and return the firstName
property like so:
let firstNames = people.map { $0.firstName }
The result is an array of Strings
—how cool is that?! :)
Challenge #02
Retrieve an array containing all
names
from theproducts
array of every person inpeople
.
Let’s try our luck by using map
again. First we would try to get an array containing all products. Maybe we try something like this:
let allProducts = people.map { $0.products }
Now we have a little problem: allProducts
is an array of arrays of products. This makes totally sense as we map over each persons products array and append that array to our resulting array allProducts
.
To join those arrays we could call joined()
on allProducts
and use map
one last time to get an array of all product names:
let allProducts = people.map { $0.products }
let joinedProducts = allProducts.joined()
let productNames = joinedProducts.map { $0.name }
This works as expected but is not so nice to read. The fact that we have to manually create 3 arrays looks very bad.
flatMap
Of course there is a much better solution just waiting to be used: flatMap
looks very similar too map
. But there is one crucial difference.
map
transforms an array and appends it to a resulting array. This works fine if the resulting array isn’t another array by itself.
flatMap
transforms an array and appends it to a resulting array just like map
. But after that it joins all arrays in the resulting arrays.
Seems like this is the perfect fit in our case, so let’s try it out:
Very cool, hm? flatMap
returns an array containing all products. On this array we then call map
to get the name of each product
.
I hope all those arrays didn’t confuse you too much and I think it’s the best to write the example by yourself in a Playground and experiment a little bit with it.
Good luck & happy coding 🎄
If you enjoyed reading this post hit the ❤️ button and share it on Twitter, Facebook or wherever you want 😊✌🏻