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