Search⌘ K
AI Features

Closure Expressions

Explore how closure expressions function as self-contained blocks of code in Swift. Learn to write and simplify closures with shorthand argument names and understand their use as completion handlers for asynchronous operations. Develop foundational Swift skills to handle advanced coding scenarios in mobile app development.

Having covered the basics of functions and methods in Swift, it is now time to look at the concept of closures and closure expressions. Although these terms are often used interchangeably, there are some key differences.

Closure expressions are self-contained blocks of code. The following code, for example, declares a closure expression and assigns it to a constant named sayHello, and then calls the function via the constant reference:

C++
let sayHello = { print("Hello") }
sayHello()

Closure expressions may also be configured to accept parameters and return results. The syntax for this is as follows:

{(<para name>: <para type>, <para name> <para type>, ... ) -> <return type> in
         // Closure expression code here
}

The following closure expression, for example, accepts two integer parameters and returns an integer result:

C++
let multiply = {(_ val1: Int, _ val2: Int) -> Int in
return val1 * val2
}
let result = multiply(10, 20)
print("result = \(result)")

Note: Closure syntax is similar to that used for declaring Swift functions with the exception that the closure expression does not have a name, the parameters and return type are included within the braces, and the in keyword ...