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