Lesson 5

Closures

A closure is a block of code that can be passed around and used in your code. Functions are special cases of closures. Closures in Swift are similar to blocks in Objective-C and can capture any constants and variables in their enclosing scope.

Function Types

In the last lesson you learned about functions—which are a special case of closures. Just like primitive data types Int, String, Double, and so on, functions have their own data types in Swift. The data type of a function is called a function type and is simply a collection of the parameters and return values of the function. For example, if given the function cubeNumber:

func cubeNumber (inputValue:Int) -> Int
{
    return inputValue * inputValue * inputValue
}

its function type is simply (Int) -> Int.

It is possible for different functions to have the same function type. In the following example, you can see that the function type for another function called squareNumber is exactly the same as for cubeNumber:

func squareNumber (inputValue:Int) -> Int
{
    return inputValue * inputValue
}

Function types are first class data types. You can declare a variable to be of a function type and assign an appropriate function to that variable as follows:

var mathFunction: (Int) -> Int = squareNumber

Function types can be used as parameters to functions as well as return values.

Closure Types

There are three types of closures in Swift: global closures, nested closures, and closure expressions. Each of these will be ...

Get Swift iOS 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.