Adding computed properties in Swift - Time & Space Complexity
When we add computed properties in Swift, we want to know how much extra work the program does as it runs.
We ask: How does the time to get the computed property change when the input changes?
Analyze the time complexity of the following code snippet.
struct Numbers {
var values: [Int]
var sum: Int {
var total = 0
for num in values {
total += num
}
return total
}
}
This code defines a computed property sum that adds all numbers in an array each time it is accessed.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the
valuesarray to add each number. - How many times: Once for every element in the array each time
sumis accessed.
As the array gets bigger, the time to calculate sum grows 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; doubling items doubles the work.
Time Complexity: O(n)
This means the time to get the computed property grows in a straight line with the size of the array.
[X] Wrong: "Accessing a computed property is always fast and constant time."
[OK] Correct: Computed properties run code each time, so if they loop over data, the time depends on the data size.
Understanding how computed properties affect time helps you write clear and efficient code, a skill valued in many coding challenges.
What if we stored the sum in a variable and updated it only when the array changes? How would the time complexity of accessing the sum change?