Swift closure
Closures are self-contained blocks of functional code that can beused in code or used as parameters to pass values.
Closures in Swift are similar to code blocks in C and Objective-C and anonymous functions in some other programming languages.
Global functions and nested functions are actually special closures.
Closures take the following forms:
Global function |
Nested function |
Closure expression |
---|---|---|
There is a name but no value can be captured. |
If you have a name, you can also capture values within a closed function. |
Anonymous closures, using lightweight syntax, can capture values according to the context. |
Closures in Swift have many optimizations:
Infer parameters and return value types based on context
An implicit return from an one-line expression closure (that is, the closure body has only one line of code, return can be omitted)
You can use a simplified parameter name, such as $0, $1 (starting with 0, representing the I th parameter.)
Provides trailing closure syntax