Mutating methods for value types in Swift - Time & Space Complexity
We want to understand how the time it takes to run mutating methods on value types changes as the data size grows.
How does changing a value type's data inside a method affect the work done?
Analyze the time complexity of the following code snippet.
struct Counter {
var counts: [Int]
mutating func incrementAll() {
for i in counts.indices {
counts[i] += 1
}
}
}
var counter = Counter(counts: [1, 2, 3, 4, 5])
counter.incrementAll()
This code defines a value type with an array and a mutating method that increases each number by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array to increment each element.
- How many times: Once for each element in the array.
As the array gets bigger, the method does more work because it updates every element.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The work grows directly with the number of elements; doubling elements doubles the work.
Time Complexity: O(n)
This means the time to run the mutating method grows in a straight line with the size of the array.
[X] Wrong: "Mutating a value type is always slow because it copies the whole data every time."
[OK] Correct: Swift uses copy-on-write optimization, so the actual work depends on what the method changes, not copying everything each time.
Understanding how mutating methods work helps you explain how your code handles data changes efficiently, a useful skill in many coding discussions.
"What if the mutating method only changed one element instead of all? How would the time complexity change?"