Quick Swift Tip: using CompactMap

A small and fast tip to use the CompactMap operator in a clever way

Alessandro Manilii
2 min readDec 2, 2022
Photo by ArtHouse Studio: https://www.pexels.com/it-it/foto/uomo-caffe-vintage-alla-ricerca-4905089/

Very often in apps could happen to present on screen the value of a variable to the user in a UILabel. Sometimes the model holding that value is more elaborate and allow you to choose between different value if one of them is not available.

Let’s take this model for example:

You are requested to show in a label the firstName, if available, otherwise use the lastName, if available, otherwise the nickName , otherwise a placeholder… pretty boring stuff I know.

A naive and honestly quite common way to solve the problem would be to use this kind of code:

This solution works but it is not elegant at all… soooo… compactMap to the rescue!

--

--

Alessandro Manilii

I’m an Italian professional iOS Developer, iOS Tech Lead at Wakala — Join Medium from the following link: https://medium.com/@alessandromanilii/membership