Selecting a closure based on results
In the final example, we will pass two closures to a method, and then, depending on some logic, one or possibly both of the closures will be executed. Generally, one of the closures is called if the method was successfully executed and the other closure is called if the method failed.
Let's start by creating a type that will contain a method that will accept two closures and then execute one of the closures based on the defined logic. We will name this type TestType
. Here is the code for the TestType
type:
class TestType {
typealias ResultsClosure = ((String) -> Void)
func isGreater(numOne: Int, numTwo: Int, successHandler: ResultsClosure,failureHandler: ResultsClosure) {
if numOne > numTwo {
successHandler("\(numOne) is greater than \(numTwo)")
}
else {
failureHandler("\(numOne) is not greater than \(numTwo)")
}
}
}
We...