Swift Language Closures Syntax variations

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The basic closure syntax is

{ [capture list] (parameters) throws-ness -> return type in body }.

Many of these parts can be omitted, so there are several equivalent ways to write simple closures:

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 }
  • The capture list can be omitted if it's empty.
  • Parameters don't need type annotations if their types can be inferred.
  • The return type doesn't need to be specified if it can be inferred.
  • Parameters don't have to be named; instead they can be referred to with $0, $1, $2, etc.
  • If the closure contains a single expression, whose value is to be returned, the return keyword can be omitted.
  • If the closure is inferred to throw an error, is written in a context which expects a throwing closure, or doesn't throw an error, throws can be omitted.
// 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 }


Got any Swift Language Question?