Swift Closures
We can think of closure as simply another way to write a function. It is simply a block of code that can be passed around to other functions.
No parameter
Let's say a simple function that receives no parameter and returns void:
func doSomething() {
//Do some work
}
This can be written in a closure syntax:
let doSomething = {
//Do some work
}
this assigns the block/closure to doSomething can now be called just like a regular function.
With parameter
If a function contains a single or multiple parameters:
func getTotalOf(firstNumber: Int, secondNumber: Int) -> Int {
return firstNumber+secondNumber
}
let result = getTotalOf(firstNumber: 1, secondNumber: 2)
print(result) //3
Function with parameter
This is how you would write it in closure:
let getTotalOf = { (firstNumber: Int, secondNumber: Int) in
return firstNumber+secondNumber
}
// We can call it just like the function above:
let result = getTotalOf(firstNumber: 1, secondNumber: 2)
print(result) //3
Closure with parameter