reduce combines a collection into one accumulated value.

Sum values with reduce

shipping
reduced_total.swift
Replay: real traced execution (multi-file project)
let shipping = 4
let prices = [12, 8, 5]
let subtotal = prices.reduce(0) { running, price in
    return running + price
}
let total = subtotal + shipping
let message = "total=\(total)"

print(message)
let shipping = 0
let prices = [12, 8, 5]
let subtotal = prices.reduce(0) { running, price in
    return running + price
}
let total = subtotal + shipping
let message = "total=\(total)"

print(message)
let shipping = 9
let prices = [12, 8, 5]
let subtotal = prices.reduce(0) { running, price in
    return running + price
}
let total = subtotal + shipping
let message = "total=\(total)"

print(message)
  1. shipping ← 4, prices ← [12, 8, 5], subtotal ← 25, total ← 29, message ← total=29

    1let shipping→ 4 = 4  //@shipping=0, 92let prices→ [12, 8, 5] = [12, 8, 5]3let subtotal→ 25 = prices[12, 8, 5].reduce(0) { running, price in4    return running + price5}6let total→ 29 = subtotal25 + shipping47let message→ total=29 = "total=\(total29)"89print(messagetotal=29)
    outputtotal=29
  1. shipping ← 0, prices ← [12, 8, 5], subtotal ← 25, total ← 25, message ← total=25

    1let shipping→ 0 = 02let prices→ [12, 8, 5] = [12, 8, 5]3let subtotal→ 25 = prices[12, 8, 5].reduce(0) { running, price in4    return running + price5}6let total→ 25 = subtotal25 + shipping07let message→ total=25 = "total=\(total25)"89print(messagetotal=25)
    outputtotal=25
  1. shipping ← 9, prices ← [12, 8, 5], subtotal ← 25, total ← 34, message ← total=34

    1let shipping→ 9 = 92let prices→ [12, 8, 5] = [12, 8, 5]3let subtotal→ 25 = prices[12, 8, 5].reduce(0) { running, price in4    return running + price5}6let total→ 34 = subtotal25 + shipping97let message→ total=34 = "total=\(total34)"89print(messagetotal=34)
    outputtotal=34
reduce The `reduce` method starts with an initial value, then folds each element into that running result.