An Introduction to Functional Swift (pt. 2)

In the first part of this delving into functional programming, I discussed its merits. This time we’ll actually be getting into some code! As a refresher to returning readers, or a short synopsis for new readers, FP at its core is simply dialing the state down as far as possible and replacing it with behavior or computation.

The biggest hurdle that prevented me from understanding the basics of FP was getting my mind around the fact that functions can be anything — when we think of functions in Swift, we think of this declaration:

public func doSomething(with x: Int) {
  //do something

when in reality, functions can be variables, parameter, closures, and return values. Again, this goes against the basics of what we’re told in school: if f(x) = y, f is a function that takes in a value x and returns a value y. In reality, with Swift’s relatively verbose type inference, neither x, nor y need to be actual values.

A great example of this that helped me fully understand the ideas behind functional programming is the operators in the CocoaPod, LithoOperators, which made functional programming much more intuitive for me. Take, for example, the compose operators:

infix operator >>>: LeftwardAssociation
public func >>>(_ f: @escaping (T) -> U, _ g: @escaping (U) -> V) -> (T) -> V {
    return { t in 

This is an infix operator that takes in two functions, (A) -> B and (B) -> C, and creates a new function that composes the two. You can take any two functions and chain them together, and then chain that function with another, and so on. This encourages the developer to think of computation in discrete stages, and therefore makes it easier to test (it is easier to identify where an error occurs in your code), and more readable — one big function with a single name alluding to input and output abstracts away everything accept for the first and last line in a function’s body. Naming many smaller, simpler functions and chaining them together provides a far more readable interface where any developer can infer the computation of a function call without actually looking at the function. Any iOS programmer with some spare time should take a look at the CocoaPod linked above, there are something like 40 different operators that make doing common operations like this a lot easier and readable.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: