Rudiger Rudiger - 7 months ago 16
Swift Question

Swift: definition and syntax of functions vs. closures

Is this a function or a closure?

let triple: Int -> Int = {
(number: Int) in // What is this?
let result = 3 * number
number
return result
}

triple(1)

Answer

1: It's a closure.

Examples:

func aFunction() -> () {
    // do something
}

let aClosure:() -> () = {
    // do something
}

Functions are actually a special case of closures. You can write a closure without a name by surrounding code with braces ({}). Use in to separate the arguments and return type from the body.

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

2: "in" is just the notation chosen to represent where the arguments/return type end, and the body of the closure begins. It has nothing to do with inout.

Comments