Closures
In Swift, functions are considered first-class citizens, meaning that they can be treated in the same as any other type. They can be assigned to variables and passed in and out of other functions. When treated this way, we call them closures.
Closures as variables
The simplest way to capture a closure in a variable is by defining the function and then using its name to assign it to a variable:
func double(input: Int) -> Int { return input * 2 } var doubleClosure = double println(doubleClosure(2)) // 4
As you can see, doubleClosure
can be used just like the normal function name after it is assigned. There is actually no difference between using double
and doubleClosure
.
If you look at the type of doubleClosure
by option-clicking on the name, you will see that the type is defined as (Int) -> Int
. The basic type of any closure is (ParamterType1, ParameterType2, …) -> ReturnType
.
Using this syntax, we can also define our closure inline as:
var doubleClosure2 = { ...