0
0
Swiftprogramming~5 mins

Computed properties in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Computed properties
O(1)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
1010 multiplications (if accessed 10 times)
100100 multiplications (if accessed 100 times)
10001000 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.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how computed properties work helps you explain how your code runs efficiently and clearly, a skill valued in real projects and interviews.

Self-Check

"What if the computed property performed a loop over an array inside it? How would the time complexity change?"