Var for variables (mutable) in Swift - Time & Space Complexity
Let's see how using var for variables affects the time it takes for a program to run.
We want to know how the program's steps grow when we change or update variables.
Analyze the time complexity of the following code snippet.
var total = 0
let numbers = [1, 2, 3, 4, 5]
for number in numbers {
total += number
}
print(total)
This code adds up all numbers in an array using a mutable variable total.
Look for loops or repeated steps.
- Primary operation: Adding each number to
totalinside the loop. - How many times: Once for each number in the array.
As the list of numbers gets bigger, the program adds more numbers one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input size grows.
[X] Wrong: "Using var makes the code slower because variables change all the time."
[OK] Correct: Changing a variable itself is quick; the main time cost comes from how many times you do it, not that it changes.
Understanding how loops and variable changes affect time helps you explain your code clearly and think about efficiency in real projects.
"What if we replaced the for loop with a function that sums the array recursively? How would the time complexity change?"