map vs compactMap

What are the differences?

Jesus Guerra
2 min readSep 19, 2019

Contrary to the Law of Conservation of Mass and Energy… As developers, on a daily basis, we can create, transform and destroy data. Today we will focus on a couple of higher order functions that allow us to transform a collection or arrays.

map(_:)

Returns an array containing the results of mapping the given closure over the sequence’s elements.
Apple Documentation

Basically, if we have an array we can use map(_:) to transform the collection based on the “conditions” we define in the mapping closure, as result, this will return an array containing the transformed elements of the “original” array.

An important and distinctive note about map(_:) can return optional types

Examples:

In the first example, we use map(_:) to transform an array of String to an array of Int based on the character count or each name.

In the second example, we show how is that map(_:) can return optional types, by trying to map an array of String to his Int value

compactMap(_:)

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.
Apple Documentation

Basically does the same as map(_:) BUT with a big difference, it returns an array of the non-nil results

Example:

We use compactMap(_:) to transform an array of String to his Int equivalent:

Sources:

Chuck Norris can hear sign language

Thanks for reading and hope you find this article helpful. As usual, any feedback or comment is welcome. And if you want to waste some of your time, follow me on twitter @guerrix

--

--