Methods in structs in Swift - Time & Space Complexity
When we use methods inside structs, it's important to know how the time to run them changes as the data grows.
We want to find out how the method's work grows when the input changes.
Analyze the time complexity of the following code snippet.
struct NumberList {
var numbers: [Int]
func sum() -> Int {
var total = 0
for num in numbers {
total += num
}
return total
}
}
This code defines a struct with a method that adds up all numbers in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each number in the array.
- How many times: Once for each number in the array.
As the list gets bigger, the method takes longer because it adds more numbers.
| 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; double the items, double the work.
Time Complexity: O(n)
This means the method takes longer in a straight line as the list gets bigger.
[X] Wrong: "The method runs in the same time no matter how many numbers there are."
[OK] Correct: Because the method adds each number one by one, more numbers mean more work and more time.
Understanding how methods inside structs work with data size helps you explain your code clearly and shows you know how performance changes with input.
"What if the method sorted the numbers before adding them? How would the time complexity change?"