Intro to Swift Functional Programming with Bob

The tutorial I’d have written for my younger self.

Bob Lee
Bob the Developer
5 min readFeb 27, 2017

--

A veteran knows how to use tools — so can we

Last update on May 16th, 2017 | Swift 3.1

Functional programming?

You get it. People are talking about it. You google and look up the first 5 articles from the top. Frustrated, you notice most tutorials pull a vague Wikipedia definition like,

“Functional Programming is a paradigm that allows you to make your code explicit. There is no state and no mutuality”

I’ve been there my friend. In fact, I still do. I give a gentle degree of a face-palm wrapped around my mouth and respond,

Dafuq?

Prerequisite

Familiarity with closures. If you do not understand what comes after in and key signs such as $0 , you are not ready for this tutorial, I recommend you to fully understand closures in this course.

Non-Functional Programming

I’m a big fan of why. Why do we learn functional programming? Well, the best answer comes from our past. Assume you are creating an calculator app that adds an array.

// Somewhere in ViewControllerlet numbers = [1, 2, 3]
var sum = 0
for number in numbers {
sum += number
}

Okay, but what if I need to create one more?

// Somewhere in NextViewController let newNumbers = [4, 5, 6]
var newSum = 0
for newNumber in numbers {
newSum += newNumber
}

It seems like we are repeating ourselves. Long, boring, and uncenessary. You have to create sum to track the added result. It’s just atrocious. 5 lines of code. We are probably better off creating a function instead.

func saveMeFromMadness(elements: [Int]) -> Int {
var sum = 0
for element in elements {
sum += element
}

return sum
}

So when you need to use the sum feature, just call

// Somewhere in ViewController
saveMeFromMadness(elements: [1, 2, 3])
// Somewhere in NextViewController
saveMeFromMadness(elements: [4, 5, 6])

Stop right there. That’s it. You’ve tasted a functional paradigm. A functional approach is nothing more than using functions to derive the result you need.

Analogy

On Excel or Google’s Spreadsheet, to sum up values, you select cells, and call a function most likely written in the C# language.

Sum function in Excel

Okay, that’s it. Bye. Thanks for reading. 😂

Declarative vs Imperative

Finally, now, it makes sense to come up with a detailed definition of functional programming.

Declarative

We often describe functional programming as declarative. You don’t care how you got the answer. For example, a human can climb up the Mt.Everest by jumping off from a plane or work from the bottom by taking ages. You get the same result. The user has no idea how the Excel spreadsheet’s Sum function is made up off. But, it just works.

The atrocious example, a.k.a non-functional programming, we saw above is often called, imperative. It tells you how you got the answer from A → B.

let numbers = [1, 2, 3]
var sum = 0
for number in numbers {
sum += number
}

The user knows that you loop through numbers. But, is it really necessary? I don’t care how it is made. I only care about the result as long as fast and quick.

As a result, Excel and Spreadsheet incorporate a functional programming paradigm to get quick and easy answers without worrying about any implementation detail — my father wouldn’t necessarily want to deal with it when working with his company’s financial data.

Other Benefits

In the atrocious example above, we had to arbitrarily create var sum = 0 in order to track the added result within each view controller. But, is it really necessary? The value of sum constantly changes. What if I mistakenly mess around with sum? Again, as I talked about in 10 tips to become a better Swift Developer,

More variables → more memorization → more headache → more bugs → more life problems.

More variables → Easy to f up → Done

As a result, a functional paradigm ensures no mutability or no change in state when used.

Also, as you come to discover more, a functional paradigm provides a modular, easy to maintain code base.

Purpose

So, now you understand why we favor functional programming. So what? Well, in this tutorial, let’s only focus on the fundamentals. I’m not going to talk about how functional programming can be applied to user events and networking and so on. I might post tutorials how to do all those stuff using RxSwift. So stay tuned or follow me if you are new.

Real Works

You might have seen things like filter, map, reduce and so on. Well, this is how you manipulate an array using a functional approach using Filter only. Make sure you are cool with generics as well.

It’s all about getting the fundamenatals. If I can teach you how to swim in the swimming pool, you probably can in the ocean, lake, pond, maybe not in the mud. In this tutorial, If you get the fundamentals, you can create your own map and reduce or any other cool functions as you wish. You may google things up. Just that you won’t get this Bob the Developer explanation from me.

Filter

Assume you have an array.

let recentGrade = ["A", "A", "A", "A", "B", "D"] // My College Grade

You want to filter/bring and returns an array that only contains a “A” which used to make my mom happy. How do you go about that imperatively?

var happyGrade: [String] = []for grade in recentGrade {
if grade == "A" {
happyGrade.append(grade)
} else {
print("Ma mama not happy")
}
}
print(happyGrade) // ["A", "A", "A", "A"]

This is mad. I wrote this code. I do not recheck while proof reading. This is atrocious. 8 lines of code within a view controller? 🙃

I can’t even.

We have to this stop this madness and save all of you who have been doing this way. Let’s create a function that does it all. Brace yourself. We are now going to deal with closures. Let’s try to create a filter that accomplishes the same task above. Real shit happens now.

Introduction to Functional Way

Let’s create a function that takes a String array and also takes a closure whose type is (String) -> Bool . Last, it will return a filtered String array. Why? Just bear with me for another two minutes.

func stringFilter(array: [String], returnBool: (String) -> Bool) -> [String] {}

You might be quite distressed by the returnBool section. I know what you must be thinking,

So, what are we going to pass under returnBool ?

The content has been fully migrated from Medium to the personal blog. If you wish to finish reading the rest of the article and learn about protocols feel free to visit the new platform here.

--

--