Foundations
Variables and Constants
Use let for values that should not change and var for values that can be
updated later.
Compute with stored values
variables.swift
Replay: real traced execution (multi-file project)
let unitPrice = 12
let quantity = 3
var total = unitPrice * quantity
total = total + 5
print("unit=\(unitPrice)")
print("total=\(total)")
let unitPrice = 8
let quantity = 3
var total = unitPrice * quantity
total = total + 5
print("unit=\(unitPrice)")
print("total=\(total)")
let unitPrice = 20
let quantity = 3
var total = unitPrice * quantity
total = total + 5
print("unit=\(unitPrice)")
print("total=\(total)")
unitPrice ← 12, quantity ← 3, total ← 36
1let unitPrice→ 12 = 12 //@unitPrice=8, 202let quantity→ 3 = 33var total→ 36 = unitPrice12 * quantity34total→ 41 = total + 55print("unit=\(unitPrice12)")6print("total=\(total41)")outputunit=12 total=41
unitPrice ← 8, quantity ← 3, total ← 24
1let unitPrice→ 8 = 82let quantity→ 3 = 33var total→ 24 = unitPrice8 * quantity34total→ 29 = total + 55print("unit=\(unitPrice8)")6print("total=\(total29)")outputunit=8 total=29
unitPrice ← 20, quantity ← 3, total ← 60
1let unitPrice→ 20 = 202let quantity→ 3 = 33var total→ 60 = unitPrice20 * quantity34total→ 65 = total + 55print("unit=\(unitPrice20)")6print("total=\(total65)")outputunit=20 total=65
Follow the Total
unitPricestarts at12.quantitystarts at3.var total = unitPrice * quantitymakes36.total = total + 5changes it to41.- The program prints
unit=12andtotal=41. | unitPrice | initial total | after+ 5| | --- | --- | --- | | 8 | 24 | 29 | | 12 | 36 | 41 | | 20 | 60 | 65 |
let and var
`let` creates a constant. `var` creates a variable that can be assigned again.
Exercise: variables.swift
Reproduce unit=12 and total=41, then try unitPrice 8 and 20 and predict each final total.