语法变体

基本的闭包语法是

{ [ 捕获列表 ] ( 参数 ) throws-ness -> 返回类型 in body }

其中许多部分都可以省略,因此有几种等效的方法可以编写简单的闭包:

let addOne = { [] (x: Int) -> Int in return x + 1 }
let addOne = { [] (x: Int) -> Int in x + 1 }
let addOne = { (x: Int) -> Int in x + 1 }
let addOne = { x -> Int in x + 1 }
let addOne = { x in x + 1 }
let addOne = { $0 + 1 }

let addOneOrThrow = { [] (x: Int) throws -> Int in return x + 1 }
let addOneOrThrow = { [] (x: Int) throws -> Int in x + 1 }
let addOneOrThrow = { (x: Int) throws -> Int in x + 1 }
let addOneOrThrow = { x throws -> Int in x + 1 }
let addOneOrThrow = { x throws in x + 1 }
  • 如果捕获列表为空,则可以省略捕获列表。
  • 如果可以推断出它们的类型,则参数不需要类型注释。
  • 如果可以推断,则不需要指定返回类型。
  • 参数不必命名; 相反,他们可以参考 $0$1$2 等。
  • 如果闭包包含要返回其值的单个表达式,则可以省略 return 关键字。
  • 如果推断闭包是抛出错误,写在一个期望抛出闭包的上下文中,或者不抛出错误,则可以省略 throws
// The closure's type is unknown, so we have to specify the type of x and y.
// The output type is inferred to be Int, because the + operator for Ints returns Int.
let addInts = { (x: Int, y: Int) in x + y }

// The closure's type is specified, so we can omit the parameters' type annotations.
let addInts: (Int, Int) -> Int = { x, y in x + y }
let addInts: (Int, Int) -> Int = { $0 + $1 }