語法變體

基本的閉包語法是

{ [ 捕獲列表 ] ( 引數 ) 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 }