For-in loop with collections in Swift - Time & Space Complexity
When we use a for-in loop to go through a collection, we want to know how the time it takes changes as the collection grows.
We ask: How does the work increase when the list gets bigger?
Analyze the time complexity of the following code snippet.
let numbers = [1, 2, 3, 4, 5]
var sum = 0
for number in numbers {
sum += number
}
print(sum)
This code adds up all the numbers in a list using a for-in loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number to the sum inside the for-in loop.
- How many times: Once for every item in the list.
As the list gets bigger, the loop runs more times, doing more additions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the list size.
[X] Wrong: "The loop runs faster because it just adds numbers quickly."
[OK] Correct: Even simple steps add up, so more items always mean more work.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs handle bigger data.
"What if we nested another for-in loop inside this one to compare each number with every other number? How would the time complexity change?"