BSM

Mar 27 2020

Featuring:

HWS+

HWS+ is an all new service from Hacking With Swift. As of writing, it has 3 courses, which each have a few sections. Until WWDC, HackingWithSwift will publish a new section to one of the 3 courses every day, which afterwards will be every few days.
I can say, after watching all the videos that are released, that they are from really high quality(not only the resolution, also the content🙂!), and are really recommended if you want to level up in your swift and iOS development skills.
Once you are there, be sure to check out the other courses they have here


Closures: Basics

Overview

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:

myClosure()

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 questions@bdev-code.nl for any questions, feedback or if you just wanted to say hi.