Constants & Variables

Naming your data

A program is mostly data with names attached. In Swift you attach a name to a value with one of two keywords:

  • let declares a constant β€” a name whose value is set once and can never change.
  • var declares a variable β€” a name whose value you can replace later.

Swift strongly prefers let. A value that can't change is a value that can't be changed by accident β€” a whole category of bugs, gone. Xcode even warns you when you write var for something you never modify.

Rule of thumb: start with let. Switch to var only when the compiler β€” the program that turns your Swift into a runnable app β€” tells you the value actually needs to change.