Closure Expressions
Become proficient in writing and using Swift closure expressions. In addition, explore examples and see how these expressions can be used in asynchronous programming.
We'll cover the following...
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:
Press + to interact
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
...