Closure
Closures are self-contained blocks of functionality that can be passed around and used in your code.
Closures can capture and store references to any constants and variables from the context in which they are defined.
This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.
Closures Are Reference Types
Closure Expressions
Closure expressions are a way to write inline closures in a brief, focused syntax.
Escaping Closures
A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns.
When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter’s type to indicate that the closure is allowed to escape.
Closure Expressions
{ (parameters) -> return type in
statements
}
Inferring Type From Context
Because the sorting closure is passed as an argument to a method, Swift can infer the types of its parameters and the type of the value it returns.
reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1 > s2 } )
reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )
Implicit Returns from Single-Expression Closures
Single-expression closures can implicitly return the result of their single expression by omitting the return keyword from their declaration, as in this version of the previous example:
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
Shorthand Argument Names
Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure’s arguments by the names $0, $1, $2, and so on.
reversedNames = names.sorted(by: { $0 > $1 } )
Trailing Closures
A trailing closure is written after the function call’s parentheses, even though it is still an argument to the function.