Quick Swift Tip: using CompactMap
A small and fast tip to use the CompactMap operator in a clever way
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!