The map
method takes a closure as an argument, calls it for each item in the array, and returns a mapped value for the item. The returned mapped value can be of a different type from the item's type.
The following lines declare a new getGamesNames
method for our previously coded GameRepository
class that performs the simplest map operation:
public func getGamesNames() -> [String] { return getAll().map({ game in game.name.uppercaseString }) }
The getGamesNames
parameterless method returns Array<String>
. The code calls the getAll
method and calls the map
method for the result with a closure that returns the name
value for each game converted to uppercase. This way, the map
method transforms each Game
instance into a String
with its name converted to uppercase. The result is an Array<String>
generated by the call to the map
method.
The following line uses the GameRepository
instance called gameRepository
to call the previously added getGamesNames...