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" ,
    {/*from ww w . j a  v  a 2  s .  c  o 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 w  w  .j  ava  2s  .c  om*/
         (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)/*www .jav a 2 s  .c o  m*/

Result

Related Example