← Back to Swift Course | Chapter 2: Variables & Types | Lesson 1 of 8

Variables and Constants

A variable is a labeled box you can put things in and change later, while a constant is a labeled box you fill once and can never change.

Declaring Variables with var

A variable is declared with var followed by a name and a value; its value can be changed later using = again.

Example: Declaring Variables with var

markup
var score = 10
print("Initial score: \(score)")
score = 25
print("Updated score: \(score)")

Declaring Constants with let

A constant is declared with let. Once it has a value, that value can never be changed for the lifetime of the program.

Note: If you try to reassign a let, Swift refuses to compile with a clear error message.

Example: Declaring Constants with let

markup
let pi = 3.14159
print("Pi is approximately \(pi)")

Why Prefer let

Swift encourages using let wherever possible because immutable values are easier to reason about and prevent accidental changes elsewhere in the code.

Note: The Swift compiler will suggest changing var to let if it notices a variable is never reassigned.

Example: Why Prefer let

markup
let maxPlayers = 4
var currentPlayers = 1
currentPlayers += 1
print("\(currentPlayers) of \(maxPlayers) players joined")
Common Mistakes
  1. Using var for a value that never changes; Swift's compiler will even warn you to change it to let.
  2. Trying to reassign a let constant after it has already been given a value, which is a compile error.
  3. Forgetting that a constant must be given a value before it is used, even if not necessarily at the exact declaration line.
Chapter Summary
  • var declares a variable whose value can change after it is set.
  • let declares a constant whose value cannot change once assigned.
  • Prefer let by default, and only use var when the value genuinely needs to change.
  • Both variables and constants must be initialized with a value before use.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.