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

Solving algorithms with reduce

We can solve algorithms with reduce by following a functional approach. The following lines declare a new getNamesSeparatedBy method for our previously coded GameRepository class that solves an algorithm by calling the reduce method. The code file for the sample is included in the swift_3_oop_chapter_07_31 folder:

    open func getNamesSeparatedBy(separator: String) -> String { 
      let gamesNames = getUppercasedNames() 
      return gamesNames.reduce("") { 
        concatenatedGameNames, gameName in 
        print(concatenatedGameNames) 
        let separatorOrEmpty = (gameName == gamesNames.last) ? "" : 
        separator 
        return "\(concatenatedGameNames)\(gameName)\(separatorOrEmpty)" 
      } 
    }  

The getNamesSeparatedBy method receives a separator argument of the String ...

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