Combining map with reduce
The following lines show an imperative code version of a for
in loop that calculates the sum of all the highestScore values for the games. The code file for the sample is included in the swift_3_oop_chapter_07_26 folder:
var sum = 0
for game in gameRepository.getAll() {
sum += game.highestScore
}
print(sum)
The code is very easy to understand. The sum variable has a starting value of 0, and each iteration of the for in loop retrieves a Game instance from the Array<Game> returned by the gameRepository.getAll method and increases the value of the sum variable with the value of the highestScore property.
We can combine the map and reduce operations to create a functional version of the previous imperative code to calculate the sum of all the highestScore values for the games. The next lines chain a call to map to a call to reduce to achieve this goal. Take a look at the following code. The code file for the sample is included in...