O'Reilly logo

Swift 3 ObjectOriented Programming - Second Edition by Gastón C. Hillar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required