TExcelTAD
Home › Swift › Swift Variables & Constants

Swift Variables & Constants

A program stores data in named containers. Swift has two kinds:

  • var — a variable, whose value can change later.
  • let — a constant, whose value is set once and never changes.

Declaring variables and constants

swift · try it yourself
var stepsToday = 4200       // can change
let dailyGoal = 10000       // fixed

stepsToday = stepsToday + 1800
print("Steps: \(stepsToday) of \(dailyGoal)")
Steps: 6000 of 10000

Trying to change a constant is a compile-time error — Swift protects you from accidentally overwriting values:

swift · try it yourself
let maxPlayers = 4
maxPlayers = 5
error: emit-module command failed with exit code 1 (use -v to see invocation)
<source>:2:1: error: cannot assign to value: 'maxPlayers' is a 'let' constant
1 | let maxPlayers = 4
  | `- note: change 'let' to 'var' to make it mutable
2 | maxPlayers = 5
  | `- error: cannot assign to value: 'maxPlayers' is a 'let' constant

Tip: Start with let everywhere and switch to var only when you really need to change the value. Code with fewer moving parts is easier to understand — and the compiler even warns you when a var is never modified.

Type annotations

Usually Swift infers the type from the initial value. You can also write it explicitly with a colon after the name:

swift · try it yourself
let city: String = "Lisbon"
var temperature: Double = 18     // 18 becomes 18.0 because the type is Double
let isRaining: Bool = false
print(city, temperature, isRaining)
Lisbon 18.0 false

A type annotation is required when you declare a constant without giving it a value immediately. Swift then checks that it is assigned exactly once before use:

swift · try it yourself
let greeting: String
let hour = 9

if hour < 12 {
    greeting = "Good morning"
} else {
    greeting = "Good afternoon"
}
print(greeting)
Good morning

Several declarations on one line

swift · try it yourself
var x = 0, y = 0, z = 0
let red = 255, green = 128, blue = 0
x += 5
print(x, y, z)
print(red, green, blue)
5 0 0
255 128 0

Naming rules

Rule Valid Invalid
Must not start with a digit player1 1player
No spaces or operators firstName first name, first-name
Not a reserved keyword (unless in backticks) `class` class
Case-sensitive count ≠ Count —

Names may contain almost any Unicode character, so let π = 3.14159 or let café = "open" are legal. Stick to readable English names in real projects.

A variable's type never changes

Once a variable has a type, it keeps it. You can change the value, but not store a different kind of value:

swift · try it yourself
var score = 10
score = 25          // fine: still an Int
score = "high"      // error: not an Int
error: emit-module command failed with exit code 1 (use -v to see invocation)
<source>:3:9: error: cannot assign value of type 'String' to type 'Int'
1 | var score = 10
2 | score = 25          // fine: still an Int
3 | score = "high"      // error: not an Int
  |         `- error: cannot assign value of type 'String' to type 'Int'

let vs var at a glance

let var
Can be reassigned No Yes
Must be initialised before use Yes Yes
Typical use values that stay fixed: settings, results, input counters, totals, state that changes

Test yourself

Which declaration creates a value that can be changed later?

  1. let total = 0
  2. var total = 0
  3. const total = 0
  4. val total = 0

What does var price: Double = 5 store?

  1. The Int 5
  2. The Double 5.0
  3. The String "5"
  4. It does not compile

After var level = 1, which assignment fails?

  1. level = 2
  2. level += 10
  3. level = "two"
  4. level = level * 3