Swift Variables
Swift gives you two keywords for storing values, var and let, and choosing correctly between them is one of the first habits that separates safe Swift code from fragile Swift code.
Declaring Values with var and let
Every value in Swift needs a name before it can be used, and you create that name with either var or let. Use var when the value needs to change after it is first set, and use let when the value should never change once assigned. This is not just a style choice — the compiler enforces it, and any attempt to reassign a let constant is a compile-time error.
Basic declarations
var score = 10
score = 15 // fine, var can change
let maxAttempts = 3
// maxAttempts = 5 // error: cannot assign to a 'let' constantWhy Swift Favors let
Swift was designed with safety in mind, and immutability is a core part of that philosophy. When you mark something as let, you are telling the compiler — and every future reader of your code — that this value is fixed. That guarantee lets the compiler catch bugs early and lets other developers reason about your code without worrying that some far-away line might silently change it.
Type Annotations
In the examples above, Swift figured out the type of each value automatically — this is called type inference. You can also be explicit by writing a type annotation after the name, separated by a colon. This is required when you declare a variable without an initial value.
Explicit type annotations
var username: String
username = "swiftDev"
let pi: Double = 3.14159
let isReady: Bool = trueMultiple Declarations on One Line
Swift lets you declare several variables or constants of the same kind on a single line, separated by commas. This is handy for grouping related values, though most style guides recommend using it sparingly to keep code readable.
Grouped declarations
var x = 0, y = 0, z = 0
let width = 100, height = 200
print(x, y, z, width, height)- var: a mutable binding — the value can be reassigned later.
- let: an immutable binding — the value is set once and never changes.
- Type annotations (: Type) are optional when Swift can infer the type from the initial value.
- Prefer let by default; switch to var only when mutation is truly needed.
var vs let at a Glance
Exercise: Swift Variables
Which keyword is used to declare a value that can be reassigned later?