Learn

Before we define a closure let’s recall the function definition from the Functions module. This will be helpful to reference while we step through the closure definition.

func functionName(parameters) -> ReturnType { // function tasks go here }

And here is how we define a closure:

{ (parameters) -> returnType in // closure tasks go here }

Notice any similarities between the definitions of a closure and a function? A closure kind of looks like a compressed function. The parameters and return types are inside the braces, and the in keyword separates them from the body. Let’s take a look at the closure definition in-depth:

  • The open and closing braces are the beginning and end of the closure definition.
  • parameters are what gets passed into the closure, just like function parameters. They are available within the closure. These are omitted if there are no parameters.
  • The parameters are followed by an arrow and the return type (-> returnType). This is what the closure will return once execution is complete. If the closure doesn’t return anything, use the keyword Void or omit the return type and arrow entirely.
  • in is a keyword that separates the input parameters and return type from the closure execution.
  • Any tasks the closure performs follow the in keyword.

Now that we have the basic definition of a closure, let’s take a look at an example:

let myClosure = { print("This is my closure") }

This is a common way to define a closure. Closures can be assigned to variables just like any other type. We can also define a closure using type annotation:

let myClosure: () -> Void = { print("This is my closure") }

While it’s generally preferred to use type inference, it is a matter of preference how a closure is defined. Now that we have defined our closure, we can call it just like a function:

myClosure() // prints “This is my closure”

Great! Not so bad right? If you get confused about the syntax, you can always reference the definitions above.

Instructions

1.

Create a closure that takes no arguments and returns no value. Have the closure print “Hello closures!” in the console. Assign the closure to a constant named helloClosures

2.

Call the helloClosures closure in the following line.

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?