Constants and Variables
Sprout stores two kinds of facts about each habit. Some never change once set, like the habit's name, "Read". Others change every day, like the current streak. Swift makes you say which is which, and that one decision prevents a surprising number of bugs.
The rule
Start with
let; switch tovaronly when the value must change.
let makes a constant: a name bound to a value once.
var makes a variable: a name whose value can be replaced later.
let habitName = "Read"
var streak = 0
streak = streak + 1 // fine, streak is a var
habitName = "Walk" // error: habitName is a let constantA few details worth knowing:
- A
letdoes not need its value on the same line, as long as it gets exactly one value before it is used.let goal: Intfollowed later bygoal = 3is allowed. - You can declare several at once:
var done = 0, skipped = 0. - Names use camelCase:
dailyGoal,longestStreak. They cannot start with a digit or contain spaces. - If you use
varbut never change the value, Xcode warns you and suggestslet.
Why prefer let? When you read let habitName, you know that value is the same on every later line. There is nothing to track. Every var is a small question for the reader: "what is it now?"
The shortcut
For each value, ask "will this line ever need to change it?" If you cannot point to the line that changes it, use let. Then let the compiler check you: it errors when a let is changed and warns when a var never is.
The habit's name
Set when the habit is created, never edited in this screen.
let name = "Read".
The trap is making everything var "just in case". It compiles, but you lose the guarantee that makes code easy to trust.
Drills
Answer fast — trust the rule.
Which line causes a compile error?
Sprout's longest-ever streak is updated whenever the current streak beats it. Which keyword?
Is let goal: Int on one line and goal = 3 on a later line allowed?
You wrote var reminderText = "Time to read" and never change it. What does Xcode do?
Remember
- Start with
let; switch tovaronly when the value must change. - Ask: which line would change it? No such line means
let. - Making everything
varcompiles but throws away a free guarantee.
