• Intro to Swift Functional Programming with Bob
  • Originally written by Bob Lee
  • The Nuggets translation Project
  • Translator: Deepmissea
  • Proofreader: ThanksDanny, Germxu

Bob, what the hell is functional programming?

A tutorial for my younger self

Do we do what the old driver does

Functional programming?

You know. A lot of people talk about it. You Google it and look at the first five articles, and to your dismay, you find that most of the articles give only a vague Definition of Wikipedia, like:

“Functional programming is a programming paradigm that makes your code clear and unambiguous, with no variables and no states.”

Same as you, man. Actually, I did the same thing. I made a gentle face mask and whispered back,

What the hell is this?

A prerequisite for

It’s very similar to closures. If you don’t understand backward and key markers like $0, then you’re not ready to read this tutorial. You can leave for a while and find resources here to upgrade.

Nonfunctional programming

I’m a hundred thousand whys. Why learn functional programming? Well, the best answers often come from history. Suppose you want to create a calculator application that adds an array.

// Somewhere in ViewController

let numbers = [1.2.3]
var sum = 0 

for number in numbers {
 sum += number
}Copy the code

No problem, but what if I add another one?

// Somewhere in NextViewController 

let newNumbers = [4.5.6]
var newSum = 0

for newNumber in numbers {
 newSum += newNumber
}Copy the code

It looks like we’re repeating ourselves, long and boring and unnecessary. You have to create a sum to keep track of the added results. This is crushing. Five lines of code. We’d better create a function instead.

func saveMeFromMadness(elements: [Int]) -> Int {
 var sum = 0

 for element in elements {
  sum += element
 }

 return sum
}Copy the code

So, where we need to use sum, we call it directly

// Somewhere in ViewController
saveMeFromMadness(elements: [1.2.3])

// Somewhere in NextViewController
saveMeFromMadness(elements: [4.5.6])Copy the code

Stop and don’t move. Right. You have now tried the use of a functional paradigm. A function is a function that gives you the result you want.

metaphor

In Excel or Google Spreadsheet, if you want to sum some values, you need to select the table and call a function written like C#.

The sum function in Excel

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

Declarative vs. imperative

Finally, now is the time to come up with detailed functional programming definitions.

declarative

We often describe functional programming as declarative. You don’t care where the answer comes from. For example, a person climbing Mount Everest might jump out of a plane or spend years climbing from underground. You’ll get the same result. People often don’t know how Sum is made up in an Excel spreadsheet, but that’s what it is.

A cruel example of what is known as non-functional programming, we often see calls above called imperative. It tells you how to get from A to B.

let numbers = [1.2.3]
var sum = 0

for number in numbers {
 sum += number
}Copy the code

People know you loop numbers. But is it necessary? I don’t care how it’s done, I just care how fast the results come out.

As a result, Excel and Spreadsheet combine the paradigm of functional programming to get results faster and easier, regardless of implementation. (My father didn’t have to care about it when he was crunching company financials.)

Other benefits

In the crushing example above, we had to create a var sum = 0 to track the increment of each view controller. But is it necessary? Sum keeps changing, so what if I mess with the sum? Also, as I mentioned in my 10 Tips to Be a Better Swift developer,

More variables → more memories → more headaches → more bugs → more life problems.

More variables → easy to fuck → screwed

Therefore, functional paradigms ensure immutability or no change in state when used.

And, as you realize or are about to discover, the functional paradigm provides a more maintainable model for code.

purpose

Well, now you see why we like functional programming. So? Well, for this tutorial, just focus on the fundamentals. I won’t talk about functional programming for events, networking, and so on. I’ll probably post some tutorials on how to do this via RxSwift. So if you’re new, follow me and screw steady.


Real work

You’ve probably seen things like Filter, Map, Reduce, and so on. Nice, these let you process an array with filters in a functional path. Make sure your understanding of generics is equally cool.

It’s all about fundamentals. If I can teach you how to swim in a pool, you can also swim in the ocean, in a lake, in a pond, in a mud puddle (preferably not), and with this tutorial, if you learn the fundamentals, you can create your own Map and Reduce or whatever cool functions you want. You can Google things, otherwise, you won’t get an explanation from this developer named “Bob” from me.

The filter

Suppose you have an array.

let recentGrade = ["A"."A"."A"."A"."B"."D"] // My College GradeCopy the code

You want to filter/bring and return an array containing only “A”, which would make my mom happy. How do you do this in an imperative way?

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"]Copy the code

It drives people crazy. I can’t believe I wrote this code. I don’t re-check when I’m proofreading. It’s cruel. Eight lines of code in view controller? 🙃

Can’t bear to think back.

We have to stop this madness and save everyone who does what you do. Let’s create a function to do it. Cheer up. Now we have to deal with closures. Let’s try to create a filter that does the same thing. Now comes the real trouble.

An introduction to the functional approach

Now let’s create a function that has an array of type String and a closure of type (String) -> Bool. Finally, it returns a filtered array of strings. Why? I’ll tell you in two minutes.

func stringFilter(array: [String].returnBool: (String) -> Bool) -> [String] {}Copy the code

You might be particularly upset with the returnBool section. I know what you’re thinking,

So what are we passing in the return Bool?

You need to create A closure that contains an if-else statement to determine if the array contains “A”. If so, return true.

// A closure for returnBool 
let mumHappy: (String) -> Bool = { grade in return grade == "A" }Copy the code

If you want him to be shorter,

let mamHappy: (String) -> Bool = { $0= ="A" }

mamHappy("A") // return true 
mamHappy("B") // return falseCopy the code

If you are confused by the two examples above, you will not get used to this copy. You need to work out and come back. You can reread my article on closures. link

Since we haven’t finished implementing our stringFilter function, let’s pick up where we left off.

func stringFilter (grade: [String].returnBool: (String) -> Bool)-> [String] {

 var happyGrade: [String] = []
 for letter in grade {
  if returnBool(letter) {
   happyGrade.append(letter)
  }

 }
 return happyGrade
}Copy the code

Your face must be 😫. I’m saying put the knife down and let me explain. With stringFilter, you can pass mamHappy as a returnBool. Then we call returnBool(letter), passing each item a mamHappy, which is mamHappy(letter).

It returns true or false. If it returns true, add letter to happyGrade with only “A”. 🤓 This is why my mother has been so happy for the past 12 years.

Anyway, let’s finally run the function.

let myGrade = ["A"."A"."A"."A"."B"."D"]

let lovelyGrade = stringFilter(grade: myGrade, returnBool: **mamHappy**)Copy the code

Enter the closure directly

You don’t need to create a separate mamHappy. You can pass it directly on returnBool.

stringFilter(grade: myGrade, returnBool: { grade in
 return grade == "A" })Copy the code

I want to make it cleaner.

stringFilter(grade: myGrade, returnBool: {$0 == “A” })Copy the code

Meat and potatoes

Congratulations, if you’ve been here, you’ve made it. I appreciate your attention. Now let’s create a rough, well known generic filter, and you can create as many filters as you want. For example, filter words you don’t like, filter the number in the array greater than 60 but less than 100. Filter Boolean types that contain only truth values.

The best part is that it can be described in one sentence. We saved lives and time. Love it, we can work hard, but we have to work smart hard.

Generic code

If you’re uncomfortable with generic code, you’re not in the right place. It’s going fast, get to safety, and it’s called “Bob, What the hell is Generic?” And come back with some weapons.

I’m going to create a function that contains Bob generics, you can use either T or U. But you know, this is my article.

func myFilter<Bob>(array: [Bob], logic: (Bob) -> Bool) -> [Bob] {
 var result: [Bob] = []
 for element in array {
  if logic(element) {
   result.append(element)
  }
 }
 return result
}Copy the code

Let’s try to find some smart students

Apply to the school system

let AStudent = myFilter(array: Array(1..100.), logic: {$0> =93 && $0< =100 })

print(AStudent) // [93, 94, 95... 100]Copy the code

Apply to the vote count

let answer = [true.false.true.false.false.false.false]

let trueAnswer = myFilter(array: answer, logic: {$0= =true })

// Trailing Closure 
let falseAnswer = myFilter(array: answer) { $0= =false }Copy the code

The filter in Swift

Fortunately, we don’t need to create myFilter. Swift already provides us with a default. Now let’s create an array from one to a hundred, and just want even numbers less than 51.

let zeroToHund = Array(1...100)
zeroToHund.filter{ $0 % 2= =0 }.filter { $0< =50 })
// [2, 4, 6, 8, 10, 12, 14... 50]Copy the code

That’s OK. The source code

My news

I’m sure by now you’re thinking about how to use functional programming in your applications and programs. Remember, it doesn’t matter what language you use.

What you need to be clear about is how to apply functional paradigms to more areas. Before you start googling, I suggest you take a moment to burn a brain cell or two.

Now that you understand what “filter” really means, you can simply Google it and see what Map and Reduce are, and how the other functions are put together. I hope you can learn to swim in a lukewarm environment.

You’re only limited by your imagination right now. Keep thinking and Google.

The last word

Personally, this article is gold. It came when I was overwhelmed by closures and functional stuff. People like very simple principles. If you like my explanation, please share it and recommend it to more people. The more hearts I receive, the more I will be like a pump, giving greater content to everyone! Also, more hearts means more points of view based on Medium’s algorithm.

Is there an Instagram geek? I will post some of my daily updates. Welcome to add me at any time, say hello to me! @bobthedev

Swift meeting

Joao, a Portuguese friend of mine, is organizing a Swift conference in Aveiro, Portugal. Unlike many people there, the purpose of the conference was to experiment with participation. Audience and speaker can interact – bring your laptop. This is my first Swift meeting. I’m so excited! Besides, it is also economical. The event will be held from June 1 to 2, 2017. If you’re interested in learning more, feel free to check out the website here or on Twitter below.

SwiftAveiro (@SwiftAveiro) | Twitter

About me

I give detailed updates on my Facebook page. I usually post at 8 a.m. Eastern time. In 2017, I set my sights on becoming the number one iOS blog in the iOS Geek community on Medium.