O'Reilly logo

Swift 3 ObjectOriented Programming - Second Edition by Gastón C. Hillar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required