Add the values in a list
Add every item once. Repeated values still count each time they occur.
Array.reduce
Simple example
Add one, two and three.
Start1 · 2 · 3
Result6
let values = [1, 2, 3]
print(values.reduce(0, +))
6
Advertisements
Everyday examples
Add the three amounts on a receipt.
Start5 · 5 · 8
Result18
let values = [5, 5, 8]
print(values.reduce(0, +))
18
How many passengers boarded at the three stops?
Start2 · 7 · 1
Result10
let values = [2, 7, 1]
print(values.reduce(0, +))
10
How many exercise books arrived in three boxes?
Start10 · 8 · 9
Result27
let values = [10, 8, 9]
print(values.reduce(0, +))
27