0
0
Swiftprogramming~5 mins

Built-in property wrappers (@State, @Published) in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Built-in property wrappers (@State, @Published)
O(n)
Understanding Time Complexity

When using built-in property wrappers like @State and @Published, it's important to understand how their updates affect program speed.

We want to know how the time to update or notify changes grows as the number of properties or observers increases.

Scenario Under Consideration

Analyze the time complexity of updating a @Published property with multiple observers.


class Model: ObservableObject {
  @Published var value: Int = 0
}

let model = Model()

// Simulate multiple observers
for _ in 1...n {
  model.$value.sink { newValue in
    print("Value changed to \(newValue)")
  }
}

model.value = 10
    

This code sets up a @Published property and attaches n observers that react when the value changes.

Identify Repeating Operations

Look for repeated actions that affect performance.

  • Primary operation: Notifying each observer when the property changes.
  • How many times: Once per observer, so n times for n observers.
How Execution Grows With Input

As the number of observers (n) increases, the time to notify all observers grows linearly.

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

Pattern observation: Doubling the number of observers doubles the notification work.

Final Time Complexity

Time Complexity: O(n)

This means notifying observers takes time proportional to how many observers there are.

Common Mistake

[X] Wrong: "Updating a @Published property is always fast and constant time regardless of observers."

[OK] Correct: Each observer must be notified, so more observers mean more work and longer update time.

Interview Connect

Understanding how property wrappers notify observers helps you reason about app responsiveness and performance in real projects.

Self-Check

What if we changed from multiple observers to a single observer that updates multiple UI elements internally? How would the time complexity change?