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 ...
Get Swift 3 ObjectOriented Programming - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.