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 off by creating a class that will contain a method which will accept two closures and then execute one of the closures based on the defined logic. We will name this class TestClass
. Here is the code for the TestClass
class:
class TestClass { 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)") } ...