0
0
Swiftprogramming~5 mins

Generic subscripts in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Generic subscripts
O(1)
Understanding Time Complexity

When using generic subscripts in Swift, it's important to know how the time to access elements changes as the data grows.

We want to find out how the number of steps grows when we use a generic subscript to get or set values.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


struct Box {
    private var storage: [String: Any] = [:]

    subscript(key: String) -> T? {
        get { storage[key] as? T }
        set { storage[key] = newValue }
    }
}

var box = Box()
let value: Int? = box["age"]
    

This code defines a generic subscript to get or set values of any type stored in a dictionary by key.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Dictionary lookup by key inside the subscript.
  • How many times: Once per subscript access.
How Execution Grows With Input

Looking up a key in a dictionary usually takes about the same time no matter how many items are stored.

Input Size (n)Approx. Operations
10About 1 lookup step
100About 1 lookup step
1000About 1 lookup step

Pattern observation: The time to access a value stays roughly the same even as the dictionary grows larger.

Final Time Complexity

Time Complexity: O(1)

This means accessing or setting a value with a generic subscript takes about the same time no matter how many items are stored.

Common Mistake

[X] Wrong: "Using a generic subscript makes access slower as the dictionary grows because it has to check types each time."

[OK] Correct: The type check happens only once after the fast dictionary lookup, so it does not slow down with more items.

Interview Connect

Understanding how generic subscripts work and their time cost shows you can reason about flexible code without losing performance.

Self-Check

"What if the storage used an array of key-value pairs instead of a dictionary? How would the time complexity change?"