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 type and returns a String value. The code calls the getUppercasedNames method and saves the result in the gamesNames reference constant. Then...