O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

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

Closure Expression Syntax

This works, but you can clean up your code. Closure syntax follows this general form:

{(parameters) -> return type in
     // Code
}

You write a closure expression inside of the braces ({}). The closure’s parameters are listed inside of the parentheses immediately after the opening brace. Its return type comes after the parameters and uses the regular syntax. The keyword in is used to separate the closure’s parameters and return type from the statements inside of its body.

Refactor your code to use a closure expression: Create a closure inline instead of defining a separate function outside of the sorted(by:) method.

Listing 13.3 Refactoring your sorting code

import Cocoa let volunteerCounts = [1,3,40,32,2,53,77,13] ...

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