CloseHomeAboutBlogCourse
Bob I’m an iOS instructor/blogger from S.Korea.July 14 • 5 min read • Edit

No Fear Closure in Swift with Bob

So, you wanna be a functional programmer?

Introduction

Back in the days — not so long ago — I dreaded Closures. I avoided it as much as possible. Those curly braces and weird looking words like in, completion handler, @escapingseemed daunting and insurmountable. 😶

If you aren’t familiar with closure, don’t you dare worry. I will walk you through. However, I expect my readers to understand what it means to return a value with a function. If not, you may start off with my YouTube lessons on basic stuff and come back after.

Resources

Swift 4 Tutorial with Bob)

Motivation

Functional programming is trending in iOS, and closure has to do with it. What? Why? How? Well, I think we are just a bit too early to discuss the relationship. It’s like eating meat without teeth. It’s hard to swallow much of it without a robust foundation. Hopefully, I can make a real smooth transition in Part 2.

What I think you will learn

The meaning of closure, higher order function, first class function. These words may come across foreign to you. Well, let’s learn together.

Who are you, Closure?

When I explain it to my 13-year old sister, I just say that it is a function without the keyword func and without a name. From the newcomer’s perspective, however, Closures seem naked and even incomplete.

So, let’s compare how you would add two numbers in a function vs closure. Both will take two Int parameters and return one Int. Let’s begin with a function.

func addTwoNumbers(number1: Int, number2: Int) -> Int {
 return number1 + number2
}

var storedFunc = addTwoNumbers
storedFunc(5, 9) // 14

I’ve stored the addTwoNumber function into the newly created var called, storedFunc. But, how is this possible? Well, in Swift, just like many other programming languages, Swift functions are described as a first-class function. I don’t know why it is called that way, but you can store a function to a variable/constant.

However, we don’t have to use the func keyword to store a function. Indeed, we can use closure instead.

var storedClosure: (Int, Int) -> Int = { (number1, number2) in
 return number1 + number2
}

storedClosure(number1: 5, number2: 9) // 14

The above example is identical to the first example. The in keyword is used to separate the input parameters,number1 and number2 from the return part. Also, we’ve stated that the type of storedClosure is (Int, Int) -> Int. The pre-stated type tells the variable that it takes two parameters and return one Int.

I hope by now, you’ve started to grasp the idea that closure is a function without name and the func keyword. Or, you can say a function is another verbose closure. 🤔

But, the example above can be simplified, and, yes, it is still called closure.

// Shorter
var storedClosure: (Int, Int) -> Int = { return $0 + $1 }

// Super Short
var storedClosure: (Int, Int) -> Int = { $0 + $1 }

So, what the heck is $0 and $1 ? Well, it’s just a syntax by Swift. It automatically recognizes two Int parameters. The first input value is $0 and the second, $1. Also, we don’t even need to put return if you are just playing with those two parameters. However, if you want to add a bit more flare to the closure like printing something,

var storedClosure: (Int, Int) -> Int = { (number1, number2) in
 print("Hello")
 return number1 + number2

}
storedClosure(3, 5) // "Hello"

By the way, if you aren’t too sure what’s going on, you can check out my YouTube video. I speak English there.

Big Word Alert

So far, you’ve learned closures and functions are pretty much the same and both are first-class since you can store them into a variable. But also, they are called, higher order function. What? (Again, I don’t know where the name comes from). You can use closure/function as parameters and even return them.

For example, you can insert a function into a function. Let’s try to insert a printing function that return, “hello world” inside of a function. The type of function used as a parameter is () -> String

func insertSomething(closure: () -> String) {
 closure()
}

Okay, it’s time to add a function that return “hello world”

func returnHelloWorld() -> String {
 print("Hello World")
 return "Hello World"
}

Let’s run it

insertSomething(closure: returnHelloWorld) // "Hello World"

Just to recap, you’ve inserted returnHelloWorld, which is a function that returns a string value, into insertSomething. If you want to add a closure as a parameter right away, you could do this way,

var closureHelloWorld: () -> String = { return "hello" }

insertSomething(closure: closureHelloWorld) // "hello"

If you just want to add something right away, you could do this

insertSomething(closure: { return "hello world"}) // "hello world"

Last Remarks

If you want to know more about advanced closures such as CompletionHandler, @escaping, you can join the intermediate Swift course, called Learn Swift with Bob. I’ve created a chapter called, “Intro to functional programming”. feel free to join the course here.

About Me

iOS Developer from South Korea. Feel free to follow my story on Instagram or get serious on LinkedIn