Closures in iOS
Closures are self-contained blocks of functionality that can be passed around and used in your code.
Closures can capture and store references to any constant and variables from the context in which they’re defined.
Closures are special type of functions. In Swift, it has three types
- Global functions: They have a name and can’t capture value.
- Nested functions: They have a name and can capture values from their enclosing function
- Closure expressions: They don’t have name and can capture values from their surrounding context.
As global and nested closures are similar to regular functions which isn’t focus in this article. We focus the rest which is Closure expressions.
Closure expressions:
Syntax Overview:
{
(parameters) −> return type in
statements
}
It has four key components
Parameters: It is just like a parameters in a function. A closure can have zero or multiple parameters like in function.
Return data type: We need to specify the return data type in closure like a function. If you don’t want return nothing specify Void.
Keyword in: It is used to defining the parameters and return data type and before closure body.
Closure body: It has block of statements and perform an action with parameters which used wants and return the data.
// closures no param and no return type
let sayHi : () -> Void = {
print("Hi Everyone")
}
sayHi() // Hi Everyone
// closures with one param and return one value
let square: (Int) -> Int = { (value) in
return value * value
}
print(square(4)) // 16
// closures with twoparam and return one value
let sum: (Int, Int) -> Int = { (value1, value2) in
return value1 + value2
}
print(sum(4, 10)) // 14
Shorthand Argument Names:
Closure arguments can refer to a position i.e. $0, $1, $2 and so on.
let square :(Int) -> Int = {
return $0 * $0
}
print(square(4)) // 16
Implicit Return From Closures:
Single-expression closures can implicitly return the result of their single expression by omitting the return keyword from their declaration.
let square :(Int) -> Int = { $0 * $0 }
print(square(4)) // 16
For a multiline expression closure, return keyword can’t be omitted.
Trailing Closure:
If you need to pass a closure expression to a function as the function’s last argument and closure expression is too long, it can be written as trailing closure. A trailing closure is written after the function call’s parentheses (), even though it is still an argument to the function. When you use the trailing closure syntax, you don’t write the argument label for the closure as part of the function call.
func getSquareOf(value: Int, onComplete:(Int) -> Void) {
let squareVal: Int = value * value
onComplete(squareVal)
}
// 1. Usual way
getSquare(value: 4, onComplete: { squareVal in
print("Square value is \(squareVal)")
})
// 2. Trailing closure way
getSquare(value: 4) { squareVal in
print("Square value is \(squareVal)")
}