Swift Functional Programming

Swift Functional Programming

I have been working with Swift since it came out, I have been listening , reading from the people in industry about multiple programming paradigm like:
* Procedural languages
* Object-oriented programming
* Literate Programming
* Imperative Programming
* Declarative Programming
* Functional Programming
* Logical Programming

Moreover, I also listening, reading a lot during XKE and Xebia internal knowledge sharing about Functional Programming. All These piece of information were floating in my brain as one-offs, Until they finally collided and things are a lot clear for me now.

I feel like i finally understand the power of Swift. I believe that still i have reached one level of understanding. I still believe i have a lot more level to go and turn all uncovered tiles of this exhilarating journey .
What all i have found very interesting about Functional programming and Swift is a tweet “Shipping swift isn’t enough. you have to ship good Swift”.

Don’t simply strive to Swift for the sake of Reading/ Writing about Swift. Its all about go beyond to “GoodSwift”.

Its Going to be hard. We have to think a lot vs falling back into our comfortable pattern, but its really going to addicting once anyone started seeing how fun and powerful Swift is. Its completely rewiring our brain.

Table of content

Functional Programming

Functional programming is a programming paradigm or simply a style of building the structure and elements of computer programs that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.

When people talk about functional programming, they mention “Function Characteristics” like Immutable data, First class functions, Pure Function, Higher order functions, Closures , Partial Functions , Partially applied function, Currying function ,Tail call optimisation. These are programming techniques used to write functional code. Its include Monads like, Map, Flat Map, Filters, Options, Reduce. Functional Programming also mentions Parallelisation, Lazy evaluation , determinism are advantageous properties.

For now, Ignore all that. Simply we can say functional code is characterised by one most important thing, that is the absence of side effects. It doesn’t rely on data outside the current function, and it doesn’t change data that exists outside the current function. Every other “functional” thing can be derived from this property.

At the beginning when i was reading about Swift blogs and tutorials, many people talked about terms like functors and monads, those sounded alien-like to me. I started to learn Haskell to understand what they were talking about. I’m not an expert, and still learning functional programming and Swift, but I wanted to share what I’ve learned so far. Hopefully it will save you some troubles to get into the functional programming world.

Let’s start with function first.


In contrast, while Swift syntax looks a lot more like other programming languages, it can also get a lot more complicated and confusing than Objective-C.
Before I continue, I want to clarify the difference between a Swift method and function, as I’ll be using both terms throughout this article. Here is the definition of methods, according to Apple’s.


Methods are functions that are associated with a particular type. Classes, structures, and enumerations can all define instance methods, which encapsulate specific tasks and functionality for working with an instance of a given type. Classes, structures, and enumerations can also define type methods, which are associated with the type itself. Type methods are similar to class methods in Objective-C.

Whereas , Functions are standalone.

func myFunctionName(param1: String, param2: Int) -> String {
return param1 + param2

Calling Function:
var result = myFunctionName(param1, param2)

This might not seem so bad until you add a few more parameters to your function:

func hello(name: String, age: Int, location: String) {
println("Hello \(name). I live in \(location) too. When is your \(age + 1)th birthday?")

hello("Mr. Nitin", 25, "India")
From reading only hello("Mr. Nitin", 25, "India", you would have a hard time knowing what each parameter actually is.

In Swift, there is a concept of an external parameter name to clarify this confusion:

func hello(fromName name: String) {
println("\(name) says hello to you!")

hello(fromName: "Mr. Nitin")

In the above function, fromName is an external parameter, which gets included when the function is called, while name is the internal parameter used to reference the parameter inside the function execution.
If you want the external and internal parameter names to be the same, you don’t have to write out the parameter name twice, Instead, just add a # in front of the parameter name as a shortcut:

func hello(#name: String) {
println("hello \(name)")

hello(name: "Nitin")

And of course, the rules for how parameters work are slightly different for methods…


Closures in Swift are similar to blocks in C and Objective-C.
Closures are first-class objects, so that they can be nested and passed around (as do blocks in Objective-C).

Closures are typically enclosed in curly braces { } and are defined by a function type () -> (), where -> separates the arguments and the return type, followed by the in keyword which separates the closure header from its body.
{ (params) -> returnType in
{()->() in}
An example could be the map function applied to an Array:

let pandavs = ["Arjun", "Yudhishthir", "Bheem"]
(padawan: String) -> String in
"\(padawan) has been trained!"
(text: String) -> String in
"Hello \(text)"

Closures with known types:
When the type of the closure's arguments are known, you can do as follows:
func applyThreeMutliplication(value: Int, multFunction: Int -> Int) -> Int {
return multFunction(value)

applyThreeMutliplication(4, {value in
value * 3
Closures shorthand argument names:
Closure arguments can be references by position ($0, $1, …) rather than by name
applyThreeMutliplication(4, {$0 * 3})
Furthermore, when a closure is the last argument of a function, parenthesis can be omitted as such:
applyThreeMutliplication(4) {$0 * 3}

Now Let’s have quick look at How Do we declare a Closure in Swift?
As a variable:

var closureName: (parameterTypes) -> (returnType)

As an optional variable:

var closureName: ((parameterTypes) -> (returnType))?

As a type alias:

typealias closureType = (parameterTypes) -> (returnType)

As a constant:

let closureName: closureType = { ... }

As an argument to a function call:

func({(parameterTypes) -> (returnType) in statements})

As a function parameter:

array.sort({ (item1: Int, item2: Int) -> Bool in return item1 < item2 })

As a function parameter with implied types:

array.sort({ (item1, item2) -> Bool in return item1 < item2 })

As a function parameter with implied return type:

array.sort({ (item1, item2) in return item1 < item2 })

As the last function parameter:

array.sort { (item1, item2) in return item1 < item2 }

As the last parameter, using shorthand argument names:

array.sort { return $0 < $1 }

As the last parameter, with an implied return value:

array.sort { $0 < $1 }

As the last parameter, as a reference to an existing function:


As a function parameter with explicit capture semantics:

array.sort({ [unowned self] (item1: Int, item2: Int) -> Bool in return item1 < item2 })

As a function parameter with explicit capture semantics and inferred parameters / return type:

array.sort({ [unowned self] in return item1 < item2 })

Pure Function

A pure function is like a mathematical function for any certain input it will always produce the same output. The function does not depend on outside state nor is it altering outside state. In other words this is called side effect free or referential transparency. Because the output is always the same for a given input we are able to safely substitute a function call with its resulting value.
For Example :
Sum of n numbers, That is pure function and will always provide the same output for list of numbers.

let n = sum(0, [1,2,3,4,5]) // n is 15

First Class Function

Functions are first-class citizens in Swift. First-class functions simply means that functions are data. An integer: Int and a function that returns an integer: () -> Int are both types of data. Either one can be stored in a variable or constant, passed to another function as a parameter, or returned as the result of another function. This concept of "functions as data" enables the development of complex systems composed of small bits of reusable logic in an elegant and concise way.

One of the ways functions can be composed is by wrapping one function in another function.

Let's say I've defined a really expensive calculation in my application.

func getOne() -> Int {
return 1

This function will be useful in many places in my program. And since functions are just data I can easily pass it around to any other function or object that needs it.
func numPlusOne(n: Int) -> () -> Int {
return delay({ () -> Int in return n + 1 })

var three = numPlusOne(2)

for _ in 0..<100 { three() // 3 is returned 100 times but n + 1 is only calculated once } ```

Partial or Partially Applied Function & Currying Function

The term is “curry” is not only a delicious Southeastern Asian cuisine, it also refers to translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument. Obviously.

Let’s take a quick walk through the world of function currying in Swift, figure out what that word above really means, and then see how powerful this technique in the real world.

Here’s a normal function in Swift that takes two Ints as arguments, a and b, then adds them together:

func add(a: Int, b: Int) -> Int {
return a + b

So now, if we want to use this function, we can call it:

let sum = add(2, 3) // sum = 5

This is useful. But what if we wanted to take a list of numbers, and add 2 to each one, getting a new list back. We could create a quick list of numbers using a Range, then use a range.map to iterate through and get a new list. That would give us a chance to apply add to the integer 3 and each number in the range:

let xs = 1...100
let x = xs.map { add($0, 3) } // x = [ 4, 5, 6, etc]

That’s not horrible, but this is also a monumentally contrived example. At a first time, It feels weird to me to have to create a closure just for the sake of passing add with a default value. It could also get a little hairy if the function was more complicated, and we needed to supply more default parameters. Fortunately we can use function currying to help.

If we just look at types, we can see that add has a type of (Int, Int) -> Int.

So it takes 2 parameters of the type Int, and returns an Int. However, what we really want is something to pass to map, which takes a function of the type A -> B:

So, if we had a function that took one argument, and returned one value, we wouldn’t need to use a closure for map at all. Instead, we could pass the function to map directly. Well, we could make this work by wrapping add in a new function:

func addThree(a: Int) -> Int {
return add(a, 3)

let xs = 1...100
let x = xs.map(addThree) // x = [4, 5, 6, etc]

But i feels this is little too specific. What if we wanted to create addFour or addOneHundred. If we keep going down this way, we’d need to continue to create wrapper functions for each integer we want to use.

It would be nicer to be able to build something that could be applied more generally for any integer. We can do this by writing our functions to return other functions.

To illustrate this, let’s start by modifying that original method:

func add(a: Int) -> (Int -> Int) {
return { b in a + b }

let’s redefined our function as one that takes a single argument. The return value is a function that takes a single argument and returns the sum of a (passed by name to the function), and b (passed to, and named by, the closure). This means two things:

If we want to satisfy all of the arguments for the function and call it immediately, we now need to separate the arguments with parenthesis:

let sum = add(2)(3) // sum = 5

It also lets us “partially apply” the add function. This means that passing one argument to add returns a new function that accepts the next argument. Once that argument is satisfied, this new unnamed function finally returns the result.

What’s the benefit of this? Well, it allows us to create smaller functions out of larger functions by reducing the number of arguments needed. Our addTwo function definition, for example, can easily become a simple let:

let addTwo = add(2)

And now addTwo is a function that takes a single Int argument, and returns an Int, which means we can still pass it directly to map:

let addTwo = add(2)
let xs = 1...100
let x = xs.map(addTwo) // x = [3, 4, 5, 6, etc]

There’s still one more change we can make that will (arguably) improve our add function. Right now, we’re manually creating and returning the closure, and giving our function an unintuitive signature. But Swift actually supports this kind of function out of the box. We can bring our function definition back to something a little closer to what we started with, without losing the currying functionality:

func add(a: Int)(b: Int) -> Int {
return a + b

This function is equivalent to our earlier implementation that had the closure, with the exception that now you need to name the second parameter:

let sum = add(2)(b: 3) // sum = 5

In fact, at the time of this writing, there is no way to define the function so that you can omit the external name.

This is fairly gross, but in this case it doesn’t impact us much at all. We can still pass the partially applied function to map as we did before.
func add(a: Int)(b: Int) -> Int {
return a + b

let addTwo = add(2)
let xs = 1…100
let x = xs.map(addTwo) // x = [3, 4, 5, 6, etc]
Ohhh, Great, but what about functions I don’t own

If you don’t own the function you’re working with or if you don’t want the function to be curried by default (because let’s be honest, that calling syntax is funky), you might think you’re out of luck.

But I have good thought: you can implement a function that takes an existing function as a parameter, and returns a curried wrapper around that function.

The same basic technique that we used to create our own curried function in the first place.

Let’s pretend that instead of add, the free function that we defined above, we’re dealing with NSNumber.add, a class method that I’m totally making up for the sake of demonstration:

extension NSNumber {
class func add(a: NSNumber, b: NSNumber) -> NSNumber {
return NSNumber(integer: a.integerValue + b.integerValue)

So now, if we decide that this function should be curried for some specific use case (like being partially applied for map), we want to be able to do that.

First thing we need to do is define a function that takes a function of the same type as NSNumber.add as an argument. When you strip away the naming, you end up with (NSNumber, NSNumber) -> NSNumber. This will let us pass NSNumber.add into it directly. We’ll name this argument localAdd internally to avoid confusion:

func curry(localAdd: (NSNumber, NSNumber) -> NSNumber) {

Then we can add the return value, which is a function that takes an NSNumber and returns a new function. That function should take an NSNumber and return an NSNumber. The type we end up with is (NSNumber -> (NSNumber -> NSNumber))

func curry(localAdd: (NSNumber, NSNumber) -> NSNumber) -> (NSNumber -> (NSNumber -> NSNumber)) {

Then we can use the trick from earlier and start returning closures:

func curry(localAdd: (NSNumber, NSNumber) -> NSNumber) -> (NSNumber -> (NSNumber -> NSNumber)) {
return { a: NSNumber in
{ b: NSNumber in
return localAdd(a, b) // returns an NSNumber

So a and b represent the two NSNumber instances that will be passed to localAdd. So now, we could curry our NSNumber.add function with our new curry function:
let curriedAdd = curry(NSNumber.add)
let addTwo = curriedAdd(2)

let xs = 1…100
let x = xs.map(addTwo) // [3, 4, 5, 6, etc]
This works really well, but we can actually use Generics to generalize our curry function to take arguments of any type.

To start, we should figure out how many types we need. In this case, we want to pass two variables and return a third. Generic types are usually shown as uppercase letters, so we’ll use A, B, and C. Replacing the explicit NSNumber types with these generic types:

func curry<A, B, C>(f: (A, B) -> C) -> (A -> (B -> C)) {
return { a: A in
{ b: B in
return f(a, b) // returns C

Now, to clean things up, we can take advantage of Swift’s type inference to remove the inner types:

func curry<A, B, C>(f: (A, B) -> C) -> (A -> (B -> C)) {
return { a in
{ b in
return f(a, b)

We can also take advantage of the implicit return values for single line closures and move the whole thing onto one line:

func curry<A, B, C>(f: (A, B) -> C) -> (A -> (B -> C)) {
return { a in { b in f(a, b) } }

Finally, the parenthesis in the return value are optional, so we can remove them as well:

func curry<A, B, C>(f: (A, B) -> C) -> A -> B -> C {
return { a in { b in f(a, b) } }

Interestingly enough, since we’ve made our function completely generic, this is actually the only way we could have possibly written the implementation in order to get it to compile. So the entire concept is encoded directly into the types. We have no idea what C is, so the only way we know of to create an instance of that type is to use f. We also don’t know what A or B are, so the only way we can get values to pass to f are to use a and b. That’s insanely powerful, since it means we can’t mess it up.

Also, since this function now works with any function that matches the type (A, B) -> C, we can use it on any function that matches this type signature. Including the functions that power the standard operators. So, if we really want to get wacky, we can re-write everything we’ve done so far like so:

let add = curry(+)
let xs = 1...100
let x = xs.map(add(2)) // [3, 4, 5, 6, etc]

This is super long. Wrap it up
[…] currying is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument.

We have a function that takes multiple arguments. We then change that function so that it only takes one argument, and returns a function that takes the next argument, and so-on and so-forth until all arguments are satisfied. At that point (and only at that point), the calculations are performed, and a value is returned. We handled this for 2 arguments, but it’s the same process for as many arguments as you can throw at your functions.

Higher Order Function

These are functions that you pass as arguments to other functions. In this simple example, filter requires that you pass a higher-order function.

Imagine that we need to calculate the sum of all the numbers from 1 to 100 whose squares are divisible by 4. In Swift, we could do that in the following way:
let result = reduce(1…100, 0) {
($1 * $1) % 4 == 0 ? $0 + $1 : $0

println(result) // 2550
But what does this cryptic syntax mean? The syntax is actually very easy to understand once we know what ‘reduce’ is and how it works. It’s just a simple higher order function.

Higher order function is a fancy name for a function that accepts another function as an argument or returns another function. While reading and listening about functional programming, I can't avoid remembering Higher Order Functions.

These functions are nothing new, of course. In fact, Cocoa and Cocoa Touch developers had been using some of them even before Swift was introduced. NSArray’s ‘enumerateObjectsUsingBlock:’ is one such example. So why would anyone bother to write about higher order functions in Swift?

What next?

Although I believe we covered a lot of things in this blogs, It will be better to play around first with what we discussed here so far. Let’s Explore more in upcoming blogs by diving deeper in these Swift Functional Programming ocean.

Leave a Reply

Your email address will not be published. Required fields are marked *