0
0
Swiftprogramming~5 mins

WrappedValue and projectedValue in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: WrappedValue and projectedValue
O(1)
Understanding Time Complexity

We want to understand how the time it takes to access and use wrappedValue and projectedValue changes as the program runs.

Specifically, how does the cost grow when these properties are used in Swift property wrappers?

Scenario Under Consideration

Analyze the time complexity of accessing wrappedValue and projectedValue in this property wrapper example.


@propertyWrapper
struct Wrapper {
  var value: Int
  var wrappedValue: Int {
    get { value }
    set { value = newValue }
  }
  var projectedValue: String {
    "Value is \(value)"
  }
}

struct Example {
  @Wrapper var number: Int
}
    

This code defines a property wrapper with wrappedValue and projectedValue, then uses it in a struct.

Identify Repeating Operations

Look for repeated actions when accessing these properties.

  • Primary operation: Accessing wrappedValue or projectedValue calls a simple getter or setter.
  • How many times: Each access is a single operation, no loops or recursion involved.
How Execution Grows With Input

Accessing wrappedValue or projectedValue always takes the same small number of steps, no matter how many times or what values are involved.

Input Size (n)Approx. Operations
1010 simple property accesses
100100 simple property accesses
10001000 simple property accesses

Pattern observation: The time grows directly with the number of accesses, but each access is quick and constant.

Final Time Complexity

Time Complexity: O(1)

This means each access to wrappedValue or projectedValue takes a fixed amount of time, no matter what.

Common Mistake

[X] Wrong: "Accessing projectedValue is slower because it creates a new string every time."

[OK] Correct: While projectedValue may compute a value, this computation is simple and constant time, so it does not grow with input size.

Interview Connect

Understanding how property wrappers work under the hood helps you explain performance clearly and confidently in interviews.

Self-Check

What if projectedValue computed a value by looping over a large array? How would the time complexity change?