O'Reilly logo

Swift 3 ObjectOriented Programming - Second Edition by Gastón C. Hillar

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

Chaining filter, map, and reduce

We can chain filter, map, and reduce. The following lines declare a new summedHighestScoresWhere method for our previously coded GameRepository class that chains filter, map, and reduce calls. The code file for the sample is included in the swift_3_oop_chapter_07_30 folder:

    open func summedHighestScoresWhere(minPlayedCount: Int) -> Int { 
      return getAll().filter({ $0.playedCount >= 
      minPlayedCount }).map({ $0.highestScore }).reduce(0) { 
        sum, highestScore in 
        return sum + highestScore 
      } 
    } 

The summedHighestScoresWhere method receives a minPlayedCount argument of the Int type and returns an Int value. The code calls the getAll and filter methods to generate a new Array<Game> with only the Game instances, whose playedCount ...

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