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 value is greater than or equal to the value specified in the minPlayedCount argument. The code calls the map method to transform an Array<Game> into an Array<Int> with  the values specified in the highestScore stored property. Then, the code calls the reduce method with the initial value for the accumulated value set to 0 and a trailing closure that performs the sum task for highestScore, which we analyzed in the previous example.

The following line uses the GameRepository instance called gameRepository to call the previously added calculateGamesHighestScoresSum method to calculate the sum of the highestScores for the games that were played at least 500,000 times. The code file for the sample is included in the swift_3_oop_chapter_07_30 folder:

    let highestScoreSumFor500000 = 
    gameRepository.summedHighestScoresWhere(minPlayedCount: 500_000) 
    print(highestScoreSumFor500000) 
..................Content has been hidden....................

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