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

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.