Swift: When the Functional Approach is NOT Right

Yesterday, I spotted what I considered to be a big Swift code smell in the codebase.

This immediately screamed out to me as a perfect opportunity to refactor into a functional solution! Wohooo! I get to do functional programming!!! Yes, I was that excited about it.

So the obvious solution was to use map here:

I was pretty proud of myself. It’s one line AND functional. But then this failed one requirement that I needed for animating the images – the array had to be an array of UIImages [UIImage], but this returned an array of OPTIONAL UIImages [UIImage?].

So I googled around, and the accepted functional solution for getting the array of non-optional UIImages was this:

This works, but I was just not happy about this. It’s long, clunky, and I hate having to force unwrap the optional here even though it is safe. The main issue, however, is that it just doesn’t seem as simple or efficient as the original for-loop. This can be seen clearly in the playground:

Maybe I’m doing this wrong, but I ended up keeping the for-loop. Lesson learned: sometimes the for-loop is the right solution in Swift. Of course I might be missing something here, so happy to hear your thoughts in the comments!

Update

As several have pointed out in the comments below and on Twitter, using Swift 2.0’s flatMap is the functional solution here:

I’ll be honest here though, and say that every time I read something about flatMap, I still don’t fully understand what it does or how it works. It’s just not coming naturally to me like map or filter does. I have no idea why it works here, so I’ll have to research this more.

This brings me to the conclusion that again, I’m not sure this is the best way for code readability. If someone else who is less knowledgeable in Swift and functional programming looks at my code, will they understand what is happening here? Meanwhile, I know for sure everyone will understand the for-loop solution at first glance.

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.