What are Closures in Swift 3? (Part 1)

Wilson Balderrama
2 min readSep 28, 2016

Closures are independent blocks of functionality that can be passed around and used in your code.

The structure of a Closure is like the following:

{ (parameters..) -> return type in 
// code
}

A really important aspect is that every closure has a type.

Let’s see some use of them in code, we have a function called sayHello which accepts as parameters a String and a Closure, the only labor sayHello function does is call the closure with its argument String.

Now let’s create the closure and one thing to notice is that sayHello function expects a closure whose type is (String) -> Void that means that the closure needs to be constructed according this type: accepts only one parameter with String type and return Void

In the above code we have created a constant called myClosure that will hold the independent block of functionality which accepts a String and returns Void and print a message concatenating the person String passed by.

So now that we have all the code set up in place let’s use them, we call sayHello function with the arguments: a literal String and myClosure constant and finally outputs the string “Hello Wilson”:

But there is lightweight to create closures, instead of creating the closure in a constant, we could have created it along the sayHello calling, like so:

In this way we didn’t create a constant or variable for the closure instead we create the closure as inline.

There more characteristics about Closures that I’d like to cover in other posts, that’s it for now, until next time!

--

--

Wilson Balderrama

I like to run everyday while listening podcasts or audiobooks, read/write at Medium and of course I try to improve my skills as an iOS Developer everyday.