Swift - Array reduce(): return the elements inside an array as a single item

Introduction

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:

  • initial value for the result. Here, 0.0 is initially assigned to subtotal.
  • A closure that takes two arguments: The first argument takes the initial value (in this case, 0.0 ), and the second argument takes the first element in the array.

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:

Demo

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)

Result

Removing the named parameters yields the following closure:

Demo

let prices = [12.0,45.0,23.5,78.9,12.5]
var totalPrice =  prices.reduce(0.0, { $0 + $1 } )
print(totalPrice)

Result

Using an operator function, the closure can be further reduced:

Demo

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

Result

Related Example