Generic subscripts in Swift - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: Dictionary lookup by key inside the subscript.
- How many times: Once per subscript access.
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 |
|---|---|
| 10 | About 1 lookup step |
| 100 | About 1 lookup step |
| 1000 | About 1 lookup step |
Pattern observation: The time to access a value stays roughly the same even as the dictionary grows larger.
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.
[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.
Understanding how generic subscripts work and their time cost shows you can reason about flexible code without losing performance.
"What if the storage used an array of key-value pairs instead of a dictionary? How would the time complexity change?"