Coding for All
Lesson 3: Variables with var
Variables with var Use var for values that change.
1var score = 0
2score = score + 10
3print(score)
Terminal
$ swift main.swift
10
Every line, explained
var score = 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!) Our score starts at 0 but will go up, so it gets var.
score = score + 10
No let or var here: score already exists, we are just giving it a new value: 0 + 10 = 10. Trying this on a let constant would be an error!
print(score)
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.