Closures in Swift


In this Swift programming tutorial, you will learn about closures in Swift with examples.

A closure in Swift is a self-contained code block of functionality and can be passed around and used in your program. It is a special type of function, but it doesn’t have any function name.

We suggest you learn about functions in Swift before you continue this tutorial.

Below is an example of a closure:

{
  print("Good Morning")
}

In the above example, we have created a closure that prints the message Good Morning.

Declaring Swift closure

Closures are special type of function in Swift. But to declare a closure, the func keyword is not used.

Below is given the syntax for declaring a closure in Swift:

{ (parameters) -> returnType in
   // code block
}

In our above syntax

Parameters: The value that can be passed to our closure.

returnType: The type of the returned value. It can be returned from the closure.

In: This is optional. It is used to separate parameters or returnType in the closure body.

Example of closure

Below is an example of a closure:

// declare a closure
var message = {
  print("Good Morning!")
}

// call the closure
message()

Output:

Good Morning!

In the above example, we have created a closure and assigned it to a variable with the variable name message. After that, we call the closure and the print("Good Morning!") statement from the closure body is executed.

Closure with parameters

Below we are creating a closure with a parameter:

// declare a closure
var messageUser = { (name: String)  in
  print("Good Morning", name)
}

// call the closure
messageUser("Emily")

Output:

Good Morning Emily

In the above example, we have created a closure that accepts a parameter (name: String).

Below is another example, where we are passing two parameters in the closure:

// declare a closure
var messageUser = { (name: String, message: String)  in
  print(message, name)
}

// call the closure
messageUser("Emily","Good Morning")

It will give the same output as we see in the previous one.

Returning value from a closure

In all the above examples, you can see we are printing directly inside the closure body instead of returning a value. But just like regular functions, you can also return a value by mentioning the return type.

Now it’s time to see the example of a closure where we return a value.

Below is the example where we have created a closure that returns a value:

// declare a closure that calculates sum of two numbers
var calculateSum = { (num1: Int, num2: Int)  -> (Int) in
  let sum = num1 + num2
  return sum
}

// call the closure and store in the variable
var sum = calculateSum(10, 5)
print(sum)

Output:

15

In the above program, we have created a closure that takes two numbers as parameters and then returns their sum. Inside the closure body, we are calculating the sum.

The return type we provide in this example is an integer (Int) in this example.

Closure as a parameter of a function

You can also use a closure as a parameter of a function. Below is an example:

// define a function and pass closure in it
func dinnerOutside(findFood: ()->()) {
  print("Let's go for dinner to a restaurant")

  // closure call
    findFood()
}

// pass closure as a parameter of our function
dinnerOutside(findFood: {
   print("Arsalan Biriyani is 3 km away")
})

Output:

Let's go for dinner to a restaurant
Arsalan Biriyani is 3 km away

In the above example, we have created a function with the function dinnerOutside(). We pass a closure to this function as a parameter. We pass the parameter findFood and assigned the closure to it.

Trailing Closure

If the last parameter of a function is a closure, then Swift allows you to use a special type of syntax to pass it into the function. It is called trailing closure syntax.

If the code of the closure is too long and this closure needs to be used as the last parameter of a function then it can be used as the trailing closure.

Even though a trailing closure is a parameter of the function, but still the code of this type of closure is written after the parenthesis is closed.

Below is an example of trailing closure in Swift:

func showMessage(notice: String, schoolMessage: ()->()) {
   print(notice)
    schoolMessage()
}

// use of trailing closure
showMessage(notice:"Today is holiday")  {
  print("School is off")
}

Output:

Today is holiday
School is off

In the above example, we have created a function showMessage() that accepts a closure as the last parameter. As the closure is the last parameter of the function, so you can use trailing closure at the time of calling the function. In the example, we have used the trailing closure.