O'Reilly logo

Learning Swift by Andrew J Wagner

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required