map vs compactMap

What are the differences?

Jesus Guerra
Sep 19, 2019 · 2 min read

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.


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


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


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


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


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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store