A map in Swift provides a way to transform data. There are several types of map, but we’ll just look at compactMap and map today.
Both of these maps are similar in what they accomplish, that is, transform data. Often you will transform elements of a sequence into a new collection with transformed values.
To help clear this up we’ll look at some examples of when this might be useful.
Lets first look at compactMap. This method is used when you have an array that might contain nil values that you want to remove, or perhaps have data that you cannot work with. A compactMap removes the nil values leaving just the values that it can work with.
let numbers = ["1", "2", "three", "4", "five"]
let convertedNumbers = numbers.compactMap { Int($0) }
In this example we create an array of five strings (line 1).
We then call the compactMap instance method on those numbers. This part, { Int($0) }, is a closure and $0 is the first argument. compactMaps only work with a single argument, so it is always $0. This is different to a sort for example where you could compare as follows: $0 < $1.
Wrapping that in Int means that it will attempt to cast the string value to an Integer. Where that is possible, it will save the item, and where not, it will be classed as nil and then discarded because a compactMap doesn’t keep those nil elements around.
The output of this would be that the first two elements are converted to Int, “three” and “five” cannot be, so are discarded, and “4” can be:
Printing this would give:
[1, 2, 4]
Compare this to a map, this would be used as follows:
let numbers = ["1", "2", "three", "4", "five"]
let mappedNumbers = numbers.map { Int($0) }
In this example we use the same array to begin with.
On the second line we call the map instance method and have the same closure that casts the first argument $0 to an Int.
The difference here is that the map keeps nil. The output is:
[Optional(1), Optional(2), nil, Optional(4), nil]
Note that .map populates with optionals because of including nil.
Which One to Use
Deciding to use compactMap or map depends on what you need to accomplish. If you are OK working with an array of optional values with some of them being nil, then a map might be good for you. Perhaps this could be statistics where some columns of data do not contain data, but the X axis still needs to be present, even if empty. In this case, use the map.
If you do not want to work with optionals or nil, then use the compactMap. An example here is that you want a list of people who attended the last meeting so that you can send a message to them following up with some action points. For those that did not attend, you do not need to email them. If each person had a value showing that they attended a particular meeting that is nil if they didn’t, then these can be filtered out with a compactMap.
Leave a Reply
You must be logged in to post a comment.