Mar 27 2020

Closures: Basics


In this article, You will learn about creating and calling closures in Swift. But before we do that, I want to give you an overview of what closures are.

A closure is a block of code that you define, starting with a { and ending with a } . A closure is actually an ‘anonymous function’ because it is a function without a name, which it doesn’t need as it gets stored as a variable.

Creating basic closures

To create a simple closure, you would write the following:

let myClosure = {
  print("this is inside a closure")

When you want to define a closure, the beginning is just a regular variable. It is getting interesting after the = sign. After you wrote the = sign, you write { to tell swift that you are creating a closure. When you press enter, Xcode will automatically add the closing brace. Inside of the braces is the body of the closure.

Calling closures

The way you call a closure is the same as you call a function. You write the name of the variable followed by open and closing parentheses (If you want parameters, which we will cover in a later post, you enter them there). For example, when you want to call the closure we wrote above, you would write something like this:


That will print out the following when you run the code:

"This is inside a closure"

Once you created your closure, and it has been stored away, it can be called after a minute, an hour or never, depending on the situation. For example, you can say, run my code after the alert was shown, or after it was dismissed. And it could be that the alert will never show because the user didn’t do something, and then your closure will never run.

This where the basics of closures. We have learned how you can create and call closures. In the coming articles, we will see how we can use parameters, and more.

Don’t forget that you can email me at for any questions, feedback or if you just wanted to say hi.