O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required