Let vs Var
Part of the Fundamentals section of Coddy's Swift journey — lesson 4 of 86.
In Swift, you use let and var to store values.
var creates a variable — its value can be changed later:
var score = 10
print(score) // 10
score = 20
print(score) // 20let creates a constant — its value cannot be changed once set:
let name = "Alice"
print(name) // Alice
// name = "Bob" // Error! Cannot assign to 'let' constantWhen to use which?
- Use
letby default. If a value doesn't need to change, make it a constant. - Use
varonly when you know the value will need to change.
This is a best practice in Swift that makes your code safer and easier to understand.
Challenge
BeginnerCreate a constant called language with the value "Swift" and a variable called age with the value 25. Print both values on separate lines.
Cheat sheet
Use var to create a variable (value can be changed):
var score = 10
score = 20 // OKUse let to create a constant (value cannot be changed):
let name = "Alice"
// name = "Bob" // Error!Best practice: Use let by default. Only use var when the value needs to change.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input