Writing equivalent closures with simplified code

It is possible to omit the type for the closure's parameter and return type. The following lines show a simplified version of the previously shown code that generates the same result. Note that the closure code is really simplified and doesn't even include the return statement because it uses implicit return. Swift evaluates the code we write after the in keyword and returns its evaluation as if we included the return statement before the expression. Swift infers the return type. We just have to replace the existing code for the filteredBy method in the NumbersWorker class with the new code. The code file for the sample is included in the swift_3_oop_chapter_07_10 folder:

    open func filteredBy(condition: (Int) -> Bool) -> [Int] { 
      return numbersList.filter({ 
        (number) in condition(number) 
      }) 
    }  

We can go a step further and use the argument shorthand notation. This way, the closure omits the type for the parameters and its return type, takes advantage of implicit returns, and also uses the argument shorthand notation. The dollar sign followed by the argument number identifies each of the arguments for the closure. In this case, there is only one argument, so we will use $0 to reference it. Obviously, $1 would reference a second argument, $2 would reference a third argument, and so on. We just have to replace the existing code for the filteredBy method in the NumbersWorker class with the new code. The code file for the sample is included in the swift_3_oop_chapter_07_11 folder:

    open func filteredBy(condition: (Int) -> Bool) -> [Int] { 
      return numbersList.filter({ condition($0) }) 
    }

The following three pieces of code are equivalent and produce the same results. The first two versions make it easier to understand that the closure receives a number argument because we use a specific name for it:

    return numbersList.filter({ 
      (number: Int) -> Bool in 
      return condition(number) 
    }) 
 
    return numbersList.filter({ 
      (number) in condition(number) 
    }) 
 
    return numbersList.filter({ 
      return condition($0) 
    }) 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.195.236