One of the most powerful Swift language features is the ability to write code in more functional style. There’s been a lot of excitement over that in the community.
I took some time to learn functional programming at the end of last year so I can write better Swift code. I highly recommend doing the same!
I also highly recommend watching every video from the Functional Swift conference last year!
So I wanted to put together some thoughts I have on functional programming in Swift after spending some time with it!
Follow The Concepts
Functional programming is intimidating. Thanks monads and functors! However, if you go down to it’s core concepts, the idea behind functional programming is super simple:
“functional programming is a programming paradigm… that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.” – Wikipedia
So the key here is that you should write your code in a mathematical way. Your functions should have a clear input and a clear output with no global side effects like mutating objects. That’s it!
Avoid Mutable State
This is similar to the point above. Functional programming is about writing mathematical code that doesn’t have side effects.
Using structs and protocols in Swift help you avoid mutable state.
I find a lot of advanced functional code to be unreadable thanks to 5+ custom operators. There are many ways to be clever if you follow functional programming concepts.
But at the end of the day, if you’re working on a team, the most important thing is to have readable code. If an intern or just a new developer joins your team, will they be totally lost? If you focus on writing readable code (instead of being fun and clever), they should be able to contribute right away.
Remember that readability is priority over being clever (unless you’re doing a fun side project where the goal is to be fun and clever of course!).
Don’t fight the frameworks
Of course, in iOS programming, having no global side effects is not possible a lot of the time due to how the Cocoa framework is set up, and that fact that there is user input / output (in a purely mathematical world, there truly are no external side effects, but that’s not where we live!).
For example, if you’re setting up a custom formatter (e.g. currency formatter) that is used in several places in your code, it’s most efficient to use a singleton. You also have to use UIViewControllers and UIViews for the UI Layer. There are ways to isolate your logic into nice immutable components to help with the mutability of these, but don’t go overboard fighting the framework to an unrecognizable (read unreadable) state.
Learn Advanced Functional Programming
While again, you shouldn’t go crazy clever with your Swift code (unless you’re just experimenting / having fun). I highly recommend learning the extremes functional programming to understand the higher level concepts and figure out where that functional line is in Swift for you.