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 

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

Get Swift 3 ObjectOriented Programming - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.