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)
Roughly, a closure is a block of code that may capture variable values from its surrounding scope. Roughly, a function is a statically defined block of code that may use variable values from its surrounding scope.
In Swift, a closure is a special type of function without the function name. For example, { print("Hello World") } Here, we have created a closure that prints Hello World .
Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. Closures can capture and store references to any constants and variables from the context in which they're defined. This is known as closing over those constants and variables.
A closure is a function that preserves the outer scope in its inner scope.
Swift Closures are defined as follows:
{ (parameters) -> return type in
statements
}
Thus, your code sample is considered a closure by definition. However, I would rewrite it as follows by moving the return type within the curly braces:
let triple = {
(number: Int) -> Int in
let result = 3 * number
number
return result
}
triple(1)
The parameters and return type begin after the opening curly brace and end before the in keyword and the body of the closure begins after the in keyword and ends at the closing curly brace. Next, I would recommend downloading and reading iBook from iTunes which can be found at the following location:
https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With