0
0
Swiftprogramming~5 mins

Property observers (willSet, didSet) in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Property observers (willSet, didSet)
O(n)
Understanding Time Complexity

When we use property observers in Swift, we want to know how much extra work happens when a property changes.

We ask: How does the time to run grow as we change the property many times?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Counter {
    var count: Int = 0 {
        willSet {
            print("About to set count to \(newValue)")
        }
        didSet {
            print("Count changed from \(oldValue) to \(count)")
        }
    }
}

let counter = Counter()
for i in 1...n {
    counter.count = i
}
    

This code changes a property many times and runs code before and after each change.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop that sets the property count repeatedly.
  • How many times: The property is set n times, triggering observers each time.
How Execution Grows With Input

Each time the property changes, the observers run once. So if we change it 10 times, 10 observer calls happen.

Input Size (n)Approx. Operations
10About 10 observer calls
100About 100 observer calls
1000About 1000 observer calls

Pattern observation: The work grows directly with how many times the property changes.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of property changes.

Common Mistake

[X] Wrong: "Property observers run only once no matter how many times the property changes."

[OK] Correct: Observers run every time the property changes, so the total work adds up with each change.

Interview Connect

Understanding how property observers add work helps you explain performance when properties update often in real apps.

Self-Check

"What if the property observers did some heavy work inside? How would that affect the time complexity?"