Swift Functional Programming(Second Edition)
上QQ阅读APP看书,第一时间看更新

Closures

Closures are self-contained blocks of code that provide a specific functionality and can be stored, passed around, and used in the code. Closures are the equivalent of blocks in C and Objective-C. Closures can capture and store references to any constants and variables from the context in which they are defined. Nested functions are special cases of closures.

Closures are reference types that can be stored as variables, constants, and type aliases. They can be passed to and returned from functions.

The following examples present different declarations of closures in Swift from the website, http://goshdarnclosuresyntax.com:

// As a variable: 
var closureName: (parameterTypes) -> (returnType)

//As a type alias:
typealias closureType = (parameterTypes) -> (returnType)

//As an argument to a function call:
func Name({ (ParameterTypes) -> (ReturnType) in statements })

Closures and first-class, higher-order, and pure functions will be covered in detail in Chapter 2, Functions and Closures.