Adding methods in Swift - Time & Space Complexity
When we add methods to a class or struct, we want to know how the time to run those methods changes as input grows.
We ask: How does the work inside these methods scale with bigger inputs?
Analyze the time complexity of the following code snippet.
struct Numbers {
var values: [Int]
func sum() -> Int {
var total = 0
for number in values {
total += number
}
return total
}
}
This code defines a method sum() that adds all numbers in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for every element in the array.
As the array gets bigger, the method does more additions, one per number.
| 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 run the method grows in a straight line with the input size.
[X] Wrong: "Adding a method does not affect time complexity because it's just a function."
[OK] Correct: The method's code can have loops or other operations that grow with input size, so it does affect time complexity.
Understanding how methods scale helps you explain your code clearly and shows you think about efficiency, a key skill in programming.
"What if the method used two separate loops over the array instead of one? How would the time complexity change?"