Computed properties in Swift - Time & Space Complexity
Let's see how the time it takes to get a computed property changes as the input changes.
We want to know how the work grows when we access a computed property that does some calculation.
Analyze the time complexity of the following code snippet.
struct Rectangle {
var width: Int
var height: Int
var area: Int {
return width * height
}
}
let rect = Rectangle(width: 10, height: 5)
print(rect.area)
This code defines a rectangle and calculates its area using a computed property.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Multiplying two numbers (width and height).
- How many times: Once each time the computed property is accessed.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 multiplications (if accessed 10 times) |
| 100 | 100 multiplications (if accessed 100 times) |
| 1000 | 1000 multiplications (if accessed 1000 times) |
Pattern observation: Each access does a fixed small calculation, so the total work grows directly with how many times you ask for the property.
Time Complexity: O(1)
This means each time you get the computed property, it takes the same small amount of time, no matter the size of the input.
[X] Wrong: "Computed properties always take longer if the numbers are bigger."
[OK] Correct: The size of the numbers does not affect how many steps the computer takes to multiply them; it's a single operation each time.
Understanding how computed properties work helps you explain how your code runs efficiently and clearly, a skill valued in real projects and interviews.
"What if the computed property performed a loop over an array inside it? How would the time complexity change?"