Variables and Constants
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
var score = 10
print("Initial score: \(score)")
score = 25
print("Updated score: \(score)")
Login to try C/C++/Java/PHP code in the editor
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
let pi = 3.14159
print("Pi is approximately \(pi)")
Login to try C/C++/Java/PHP code in the editor
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
let maxPlayers = 4
var currentPlayers = 1
currentPlayers += 1
print("\(currentPlayers) of \(maxPlayers) players joined")
Login to try C/C++/Java/PHP code in the editor
- Using
varfor a value that never changes; Swift's compiler will even warn you to change it tolet. - Trying to reassign a
letconstant after it has already been given a value, which is a compile error. - Forgetting that a constant must be given a value before it is used, even if not necessarily at the exact declaration line.
vardeclares a variable whose value can change after it is set.letdeclares a constant whose value cannot change once assigned.- Prefer
letby default, and only usevarwhen 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: