Functions
Closures in Swift
A closure is a self-contained block of code which behaves like a function, but is never fully declared as a function.
Equivalent to anonymous functions or lambdas in other languages.
Syntax
{ (paramName: dataType, param2: dataType) -> returnDataType in
//code to execute
return value
}
Notes
Parameter data types in functions can be inferred (they do not have to be provided).
Closures are often used as parameters within functions.
With a single expression closure, the return statement can be inferred.
Closures can access values within the scope that it is declared.
Closures can be assigned to variables and lets, and called.
Example
var value1 = 3, value2 = 5
//single expression, return is omitted
var max = { (value1, value2) -> Int in value1 > value2 ? value1 : value2) }
//non single expression
var min = { (value1, value2) -> Int in
if value1 < value2{
return value1
} else {
return value2
}
}