Swift - Extract all the prices from the array and create a single string listing all of them

Introduction

To extract all the prices from the array and create a single string listing all of them.

You can write the following closure:

Demo

let prices = [12.0,45.0,23.5,78.9,12.5]
var allPrices =  prices.reduce(
    "List of prices" ,
    {/* ww w . ja  v a 2s .co  m*/
         (subString: String, price: Double) -> String in
             return ("\(subString)\n$\(price)")
     }
)
print(allPrices)

Result

Using type inference, the closure now looks like this:

Demo

let prices = [12.0,45.0,23.5,78.9,12.5]
var allPrices =  prices.reduce(
    "List of prices",
    {/* w  ww  .  ja  va 2s. c  o m*/
         (subString, price) in
             "\(subString)\n$\(price)"
    }
)
print(allPrices)

Result

Removing the named parameters further reduces the closure as follows:

Demo

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

var allPrices =  prices.reduce("List of prices",  { "\($0)\n$\($1)" } )
print(allPrices)/*w  w  w .  j  av a  2 s  .co  m*/

Result

Related Example