Swift - Array map(): transform the elements inside an array into another array

Introduction

Swift Array map() function transforms the elements from one array into another array.

Assume you have an array that contains the prices of some items:

let prices = [12.0,45.0,23.5,78.9,12.5]

to transform the prices array into another array with each element containing the dollar ($ ) sign, like this:

["$12.0", "$45.0", "$23.5", "$78.9", "$12.5"]

Use the map() function:

Demo

let prices = [12.0,45.0,23.5,78.9,12.5]

var pricesIn$ = prices.map (
     {//w  w  w. ja  va  2  s . c  om
          (price:Double) -> String in
            return "$\(price)"
     }
)
print(pricesIn$)

Result

The map() function accepts a closure as its argument.

The closure itself accepts a single argument representing each element of the original array.

Here, the closure returns a String result.

The closure is called once for every element in the array.

The preceding code can be reduced to the following:

Demo

let prices = [12.0,45.0,23.5,78.9,12.5]
var pricesIn$ = prices.map(
     {// w w  w  .j a  v  a2 s  .c om
         (price) -> String in
             "$\(price)"
     }
)
print(pricesIn$)

Result

Using the shorthand argument names, and because the closure has only a single line, the code can be further reduced as follows:

Demo

let prices = [12.0,45.0,23.5,78.9,12.5]
var pricesIn$ = prices.map (
     {//w  w  w  .  j ava  2 s  .co m
         "$\($0)"
     }
)
print(pricesIn$)

Result

Related Example