The array reduce() function returns a single value representing the result of applying a reduction closure to the elements in the array.
The following code snippet shows how to sum all the prices in the array:
let prices = [12.0,45.0,23.5,78.9,12.5] var totalPrice = prices.reduce( 0.0 , { (subTotal: Double, price: Double) -> Double in return subTotal + price } ) print(totalPrice)
The reduce() function takes two arguments:
The closure is called recursively and the result passed in to the same closure as the first argument, and the next element in the array is passed in as the second argument.
This happens until the last element in the array is processed.
The closure recursively sums up all the prices in the array.
Applying type inference reduces the closure to the following:
let prices = [12.0,45.0,23.5,78.9,12.5] var totalPrice = prices.reduce( 0.0,//from w ww . j a va 2s. c o m { (subTotal, price) in return subTotal + price } ) print(totalPrice)
Removing the named parameters yields the following closure:
let prices = [12.0,45.0,23.5,78.9,12.5] var totalPrice = prices.reduce(0.0, { $0 + $1 } ) print(totalPrice)
Using an operator function, the closure can be further reduced:
let prices = [12.0,45.0,23.5,78.9,12.5] var totalPrice = prices.reduce(0.0, + ) print(totalPrice)//from ww w . j a v a 2s . c om