Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Swift Basics  ›  Lesson

Constants and Variables

Constants & Variables 12 minlet binds a name to a value that never changes and var allows the value to be replaced, and good Swift starts with let.

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 to var only 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 constant

A few details worth knowing:

  • A let does not need its value on the same line, as long as it gets exactly one value before it is used. let goal: Int followed later by goal = 3 is 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 var but never change the value, Xcode warns you and suggests let.

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.

Sorting Sprout's habit factsStep 1 of 4
  1. 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.

quick drill

Which line causes a compile error?

quick drill

Sprout's longest-ever streak is updated whenever the current streak beats it. Which keyword?

quick drill

Is let goal: Int on one line and goal = 3 on a later line allowed?

quick drill

You wrote var reminderText = "Time to read" and never change it. What does Xcode do?

Remember

  • Start with let; switch to var only when the value must change.
  • Ask: which line would change it? No such line means let.
  • Making everything var compiles but throws away a free guarantee.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainChoosing let or var

For a Sprout habit, decide let or var for: its name, its current streak, the date it was created, and its colour (which the user can edit in settings). Explain the rule you used.