Select 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 that 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 compareClosure = ((String) -> Void) func isGreater(numOne: Int, numTwo:Int, successHandler: compareClosure, failureHandler: compareClosure) { if numOne > numTwo { successHandler("\(numOne) is greater than \(numTwo)") } else { failureHandler("\(numOne) is not greater than \(numTwo)") } } }
We begin this class by creating a type alias that defines the closure that we will use for...