O'Reilly logo

Application Development with Swift by Hossam Ghareeb

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

Think of closures as a piece of code or functionality to pass around in your code. Closures in Swift are very similar to blocks in C and Objective-C. Closures in Swift are the first class type and it is allowed to be returned or passed as a parameter. And as we will see, functions are just special instances of closures. The general formula for closures is like this:

{ (params) -> returnType in
    
    //statements
}

As you can see, we opened curly braces, and then we added the necessary parameters followed by the return type and the in keyword. Knowing this formula will help you a lot in using closures, and you will not feel any frustration using it.

This is an example of using closures in sorting the collection of data:

var nums = [10, 3, 20, 40, ...

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