We can chain solve algorithms with reduce
by following a functional approach. The following lines declare a new getSeparatedGamesNames
method for our previously coded GameRepository
class that solves an algorithm by calling the reduce
method:
public func getSeparatedGamesNames(separator: String) -> String { let gamesNames = getGamesNames() return gamesNames.reduce("") { concatenatedGameNames, gameName in print(concatenatedGameNames) let separatorOrEmpty = (gameName == gamesNames.last) ? "" : separator return "\(concatenatedGameNames)\(gameName)\(separatorOrEmpty)" } }
The getSeparatedGamesNames
method receives a separator
argument of the String
type and returns a String
value. The code calls the getGamesNames
method and saves the result in the gamesNames
reference constant. Then, the code calls the reduce
method with an empty string as the initial
value for an accumulated value. The code uses a trailing closure to...