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:) method. ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.