Closure Expression Syntax

This works, but you can clean up your code. There is no need to declare a named function; you can create a closure to pass to sorted(by:) inline – right in the method call – using closure expression syntax, like:

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

You write a closure expression inside braces ({}). The closure’s parameters are listed in 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 in its body.

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

Get Swift Programming: The Big Nerd Ranch Guide, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.