Closures are types that hold function references. The code below shows how to declare a function that accepts closures.
1
2
3
4
|
func compute(num1: Double, num2: Double,
operation: (Double, Double) -> Double) -> Double {
return operation(num1, num2)
}
|
The compute function takes three parameters. The first two are operands of type Double. The last parameter is a closure type. The closure type accepts two Doubles as parameter and returns a Double.
To invoke the above function, the following code can be used.
1
2
|
compute(5, 2, {(num1: Double, num2: Double) -> Double in
return num1 + num2})
|
Since Swift can do type inference, the following code works well.
1
|
compute(5, 2, {(num1, num2) in return num1 + num2 })
|
The return keyword is optional. The code below works equally well.
1
|
compute(5, 2, { (num1, num2) in num1 + num2 })
|
The parameters can be replaced with positional parameters like $0, $1 as follows.
1
|
compute(5, 2, {$0 + $1})
|
If the closure is the last parameter, the closure can be supplied with a syntax as follows.
1
|
compute(5, 2) { $0 + $1 }
|
For the simple example, operator functions can be used to make the compute call very concise.
1
|
compute(5, 2, +)
|
Closures in Swift allow developers to write concise and intuitive code.