0
0
Swiftprogramming~5 mins

@propertyWrapper declaration in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: @propertyWrapper declaration
O(n)
Understanding Time Complexity

We want to understand how the time it takes to use a @propertyWrapper grows as we use it more in code.

Specifically, how does the cost change when we access or set wrapped properties many times?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


@propertyWrapper
struct Capitalized {
  private var value: String = ""
  init(wrappedValue: String) {
    self.wrappedValue = wrappedValue
  }
  var wrappedValue: String {
    get { value }
    set { value = newValue.capitalized }
  }
}

struct Person {
  @Capitalized var name: String
}

var p = Person(name: "john doe")
print(p.name)
p.name = "jane smith"
print(p.name)
    

This code defines a property wrapper that capitalizes strings when set, then uses it in a struct.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Capitalizing the string when setting the wrapped property.
  • How many times: Each time the property is set, the capitalization runs once on the new string.
How Execution Grows With Input

Each time we set the property, the capitalization processes the whole string once.

Input Size (n)Approx. Operations
10 (characters)10 operations to capitalize
100 (characters)100 operations to capitalize
1000 (characters)1000 operations to capitalize

Pattern observation: The time grows linearly with the length of the string being set.

Final Time Complexity

Time Complexity: O(n)

This means the time to set the property grows in direct proportion to the string length.

Common Mistake

[X] Wrong: "Setting the property is always a quick, fixed-time action regardless of string size."

[OK] Correct: Because the wrapper modifies the string by capitalizing it, the time depends on how long the string is.

Interview Connect

Understanding how property wrappers affect performance helps you write clean code without surprises in speed as data grows.

Self-Check

"What if the property wrapper performed a more complex operation, like sorting an array, instead of capitalizing a string? How would the time complexity change?"