Tag Archives: flatMap

Swift: flatMap in action

I am working on an investment related project now. It has plenty of features, I’m not gonna go through them. One of the tasks I had was to show the tickers the user owns in a comma separated list. The problem was the data I had available didn’t contain the necessary field. So I had to iterate through a list of stock objects, and call the appropriate service method to get the ticker for every element. My code looked something like this:

It is working okay, but it is ugly, and hard to understand what it is going on at the first glance. So I started experimenting a bit with flatMap. It turned out to be pretty cool. You can do whatever you like in the closure to every single element of the array, and a new array is returned. Also ensures that there are no nil values in the result. So I ended up with this:

At first it may look strange, but actually it is easy to read, easy to understand.

Swift is awesome!