Map, Filter and Reduce in Swift
Eleazar Estrella Nov 6
Swift, as many modern languages, has implemented some beautiful functional capabilities to its core. If you are not experienced with functional paradigm, it's common to implement the classic for-loop for resolving the frequently seen problems around collection types, but that's not the Swiftiest way. So today I'm going to introduce High Order Functions which will let you simplify your code when a collection type joins in.
A Higher Order Function is a function that receive other functions as arguments or a function that returns another function as its result. We'll be using Map, Reduce and Filter in this post. Let's get started!
In many programming languages, map is the name of a higher-order function that applies a given function to each element of a functor, e.g. a list, returning a list of results in the same order.
Instead of writing a for loop and applying your business logic to each element, map takes care of that for you. It's only necessary to code the function that map will apply to each element, saving us time and lines.
Also you are able to transform your collection to another collection with a different type.
In functional programming, filter is a higher-order function that processes a data structure (usually a list) in some order to produce a new data structure containing exactly those elements of the original data structure for which a given predicate returns the boolean value true.
Continuing with saving us a lot of code, filter iterates over a collection and then returns a new collection containing those elements that have matched with the condition of our predicate.
In functional programming, fold (also termed reduce, accumulate, aggregate, compress, or inject) refers to a family of higher-order functions that analyze a recursive data structure and through use of a given combining operation, recombine the results of recursively processing its constituent parts, building up a return value.
Okey, that sounds too technical. Let me explain it in other words. What reduce function does is to combine every item of a collection in a unique value.
Let's see all of these together in action. Do you remember my previous post where I was introducing a new way to solve a common problem? Now let's do that again but using what we just learned.
So, now instead of using the classic for-loop like this:
We could just reduce this to a one single line:
It's now more elegant than before, isn't it?