Using map to transform values
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 getUppercasedNames
method for our previously coded GameRepository
class that performs the simplest map operation. The code file for the sample is included in the swift_3_oop_chapter_07_21
folder:
open func getUppercasedNames() -> [String] { return getAll().map({ game in game.name.uppercased() }) }
The getUppercasedGames
parameterless method returns Array<String>
, specified with the [String]
shortcut. 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 String
with its name converted to uppercase. The result is an Array<String>
 ...