0
0
Swiftprogramming~5 mins

Adding computed properties in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Adding computed properties
O(n)
Understanding Time 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?

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the values array to add each number.
  • How many times: Once for every element in the array each time sum is accessed.
How Execution Grows With Input

As the array gets bigger, the time to calculate sum grows because it adds more numbers.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of items; doubling items doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to get the computed property grows in a straight line with the size of the array.

Common Mistake

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

Interview Connect

Understanding how computed properties affect time helps you write clear and efficient code, a skill valued in many coding challenges.

Self-Check

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?