Map, CompactMap, and FlatMap in Swift
Swift brings us map, compactMap, and flatMaparrayOfIntegers
that all can be known as high order functions. If you do not familiar with the high order functions in Swift, you will simply make a for loop to iterate elements. But, there are better and nicer ways. Let’s dive into this topic.
We can create a simple for loop that iterates an array of integers to make a new string array.
By using a for loop;
Instead of a for loop, we can use the map function. When it is used, the code is much more readable and you will get rid of writing multiple lines of code.
Map
By using the map function;
Imagine that our arrayOfIntegers
constant has some nil values and you do not want them to be mapped to the corresponding string, but rather, ignore them.
By using the map function;
Compact Map
By using only compact map function;
By using a compact map and map function;
Flat Map
Structured it in a way that it consists of odd and even number arrays. The task is to map it into a single array without nil values.
By using only a flat map;
By using flat map and compact map functions;
Conclusion
If you need to simply transform a value to another value, then use #map#.
If you need to remove nil values, then use #compactMap#.
If you need to flatten your result one level down, then use #flatMap#.