Standard Library Patterns
Reduced Total
reduce combines a collection into one accumulated value.
Sum values with reduce
reduced_total.swift
let shipping =
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 =
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 =
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)
reduce
The `reduce` method starts with an initial value, then folds each element into that running result.