100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Swift

Variables and Constants in Swift

Learn how Swift's var and let keywords declare mutable variables and immutable constants, and why let is preferred by default.

BasicsBeginner6 min readJul 8, 2026
Analogies

Introduction

In Swift, you store values using either variables or constants. A variable, declared with the var keyword, can be changed after it is first set. A constant, declared with the let keyword, cannot be changed once a value has been assigned. Apple's official guidance is to use let whenever a value does not need to change, since immutability makes code safer and easier to reason about, and to switch to var only when mutation is genuinely required.

🏏

Cricket analogy: A var jersey number can be reassigned when a player is traded mid-season, while a let birth year is fixed forever once recorded, and Apple's guidance mirrors a scorer defaulting to fixed facts unless a value genuinely needs to change.

Syntax

swift
var mutableValue = 10
let fixedValue = 20

var username: String = "swiftDev"
let maxAttempts: Int = 3

Explanation

The var keyword tells the compiler that the value bound to that name may be reassigned later in the program. The let keyword tells the compiler the opposite: any attempt to reassign a let constant is a compile-time error. Both variables and constants can have an explicit type annotation, written after a colon, or Swift can infer the type from the initial value. Using let by default helps the compiler catch accidental mutations and makes it obvious to other readers which values are meant to stay fixed.

🏏

Cricket analogy: var telling the compiler a scoreboard total may be reassigned is like allowing live score updates after every ball, while let telling it a match's toss result cannot be reassigned is like locking that decision the instant the coin lands.

Example

swift
var score = 0
score = score + 10
print(score)

let pi = 3.14159
// pi = 3.14  // Compile-time error: cannot assign to a 'let' constant

Output

swift
10

Key Takeaways

  • var declares a mutable value that can be reassigned later.
  • let declares an immutable constant; reassigning it is a compile-time error.
  • Apple recommends using let by default and only using var when mutation is needed.
  • Both var and let can use explicit type annotations or rely on type inference.
  • Preferring immutability reduces bugs caused by unexpected state changes.

Practice what you learned

Was this page helpful?

Topics covered

#Swift#SwiftProgrammingStudyNotes#Programming#VariablesAndConstantsInSwift#Variables#Constants#Syntax#Explanation#StudyNotes#SkillVeris