Adding It Up
Total up all the numbers in an array.
1let prices = [2, 4, 6]
2var total = 0
3for price in prices {
4 total += price
5}
6print(total)
$ swift main.swift
12
Every line, explained
let prices = [2, 4, 6]- An array stores several values in one variable. The values go between square brackets, separated by commas. This one holds Ints; arrays can hold any type, as long as every item matches.
var total = 0- var creates a variable: a box whose value CAN change. The Swift rule of thumb: use let unless you truly need to change the value. (Swift even warns you if a var never actually changes!) total starts at 0 and will collect the running sum. It changes, so it must be var.
for price in prices {- for ... in visits each item, one trip around the loop per item. Each time, the loop variable holds the current item.
total += price- += adds the value on the right onto the variable on the left: 0+2=2, 2+4=6, 6+6=12. A shorter way of writing total = total + price.
}- This } closes the for loop.
print(total)- print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. All lowercase, both brackets needed, and no semicolon at the end; Swift doesn't use them. After the loop finishes, total is 12.