In Swift we have
flatMap and now
compactMap. What do each of these functions do and how can we use them? Let’s have a look at
Part 1: Map
map function takes a collection (often an array) and a function, and returns an array of items from the collection with the function applied to each item:
So for example, we could take an array of integers and a function which multiplies integers by 2:
Or given a list of names, we could capitalise them all:
[NB: If the curly brackets or $0 notation are not familiar then it’s worth reading up on closures before continuing]
The same result can be achieved by looping through each element in the array as follows:
So why use the map function?
mapis declarative. We are declaring what we want the code to do, rather than how we want it to do it (imperative). The code is therefore declaring our intent, so should be clearer and easier to understand.
mapwe could declare the resulting array with
letwhereas with a loop we need to use
var. If we don’t want this array to change after we’ve made it then this is safer code.
flatMap… coming soon!