Why let and var distinction matters in Swift - Performance Analysis
When we use let and var in Swift, it affects how the program runs over time.
We want to see how choosing between constant and variable storage changes the work done as the program runs.
Analyze the time complexity of this Swift code snippet.
func sumNumbers(_ n: Int) -> Int {
let constantValue = 5
var total = 0
for i in 1...n {
total += i + constantValue
}
return total
}
This code adds numbers from 1 to n, each time adding a constant value stored with let.
Look at what repeats as the input grows.
- Primary operation: The
forloop runs through numbers 1 to n. - How many times: Exactly n times, once for each number.
As n grows, the loop runs more times, doing more additions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with n, the number of loop steps.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input size increases.
[X] Wrong: "Using let instead of var makes the loop faster."
[OK] Correct: The choice of let or var for constants inside the loop does not change how many times the loop runs or the main work done.
Understanding how constants and variables affect program steps helps you explain code efficiency clearly and confidently.
What if we replaced the constant let constantValue with a variable var constantValue that changes inside the loop? How would the time complexity change?
Practice
let and var in Swift?Solution
Step 1: Understand
letusageletis used to declare constants, meaning their value cannot change after being set.Step 2: Understand
varusagevaris used to declare variables, which can be changed after initialization.Final Answer:
letdeclares a constant,vardeclares a variable. -> Option BQuick Check:
let= constant,var= variable [OK]
- Thinking
letcan be changed after assignment - Confusing
letandvarroles - Assuming both behave the same
Solution
Step 1: Identify Swift syntax for variable declaration
In Swift,varis used to declare variables that can change.Step 2: Check each option
let score = 10declares a constant.const score = 10andvariable score = 10use invalid keywords.var score = 10is correct.Final Answer:
var score = 10 -> Option AQuick Check:
Usevarfor changeable values [OK]
- Using let instead of var for variables
- Using non-Swift keywords like const or variable
- Syntax errors from wrong keywords
var count = 5 count = 10 print(count)
Solution
Step 1: Analyze variable declaration and assignment
countis declared withvar, so it can be changed. Initially, it is 5, then reassigned to 10.Step 2: Understand print output
The print statement outputs the current value ofcount, which is 10 after reassignment.Final Answer:
10 -> Option CQuick Check:
var allows reassignment, so output is 10 [OK]
- Thinking count stays 5 after reassignment
- Confusing var with let causing error
- Expecting nil output
let name = "Alice" name = "Bob"
Solution
Step 1: Check declaration of
namenameis declared withlet, making it a constant.Step 2: Check reassignment attempt
The code tries to assign a new value toname, which is not allowed for constants.Final Answer:
Cannot assign to 'name' because it is a constant -> Option AQuick Check:
let constants cannot be reassigned [OK]
- Assuming let variables can be reassigned
- Thinking semicolon is required in Swift
- Ignoring error messages
Solution
Step 1: Identify which values change
User ID never changes, so it should be a constant declared withlet. Score changes, so it should be a variable declared withvar.Step 2: Match declarations to requirements
let userID = 12345 var score = 0 correctly declaresuserIDwithletandscorewithvar.Final Answer:
let userID = 12345 var score = 0 -> Option DQuick Check:
Constants for fixed data, variables for changing data [OK]
- Using var for fixed values causing accidental changes
- Using let for changing values causing errors
- Mixing up which data changes
Ready to prove it?
Pass the test and this pattern moves unknown
