-Oct 5, 2016: Added FlatMap
Swift is considered a hybrid-language, so it supports multiple programming styles. For the use of Map, Filter and Reduce, I have seen it paired with ‘Functional Programming’ and ‘Higher-Order Functions’. But in this post, I will be explaining how to use the ‘map’, reduce’ and ‘filter’ function. So let’s begin with some materials!
Map is a function that applies a given operation to each item in that array and return a new array.
Take the example below – If you wanted to square each element within an array. This would be one way to do it:
What is nice about using the ‘map’ function is that it removes the need for a loop. The example below uses less code and does the exact same thing as the above code.
The difference for FlatMap vs. Map is that: FlatMap operates on the array itself and Map operates on the contents within the arrays.
Take the example below, I nested several arrays within an array. In order to access those array I have to use $0.map to access them one by one (for in loops essentially). So within this nested closure the goal is to multiply all the elements by 3.
FlatMap + Optionals
I want to point out the use of FlatMap and Optionals. Apparently FlatMap is made specifically to work with optionals within arrays. Meaning if there is nil, it will return a array and skip right over the nil!
Take the example below. I created an array that contains a lot of nils called arrayWithNil (I also had to explicitly specify what array type it was, optional string). Once flatMapped, it returned a new array that had no nil! Amazing!
Filter is exactly what it sounds like, it filters whatever object you are looking for within a given condition. Say you want to return an array that is full of grades that is over 79. You could do something like the below example:
Now, the above example works! As does this following example! The conditional within the gradesSearch function requires a loop and the object to be greater than 79 – with the filter function it cuts the code down significantly, using only the conditional with the shorthand syntax.
A great way to use ‘reduce’ is to reduce objects within an array. Say I want to combine all the elements within an array of strings. I could write a function such as the one below to do the work:
Now can we make something shorter and cleaner? Yes, absolutely! Just check the below example:
Now, you may have seen parameter names such as $0, $1,…
Those would be called the ‘shorthand syntax’, instead of long argument names you can use the shorthand syntax to really cut down on the verbosity of your code!