Generic type declaration in Swift - Time & Space Complexity
When we use generic types in Swift, we want to know how the program's speed changes as we use different data sizes.
We ask: How does the time to run grow when the input size grows?
Analyze the time complexity of the following code snippet.
struct Box<T> {
var items: [T]
func countItems() -> Int {
return items.count
}
}
let intBox = Box(items: [1, 2, 3, 4, 5])
print(intBox.countItems())
This code defines a generic Box that holds items of any type and counts how many items it has.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the count property of the array.
- How many times: Once per call to
countItems().
The count property of an array in Swift is stored and accessed instantly, so the time does not grow with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The operation count stays the same no matter how many items are in the box.
Time Complexity: O(1)
This means counting items takes the same short time no matter how many items there are.
[X] Wrong: "Counting items in a generic container always takes longer if there are more items."
[OK] Correct: In Swift, the array's count is stored and accessed instantly, so counting does not slow down with more items.
Understanding how generic types work with time complexity helps you explain how your code handles different data sizes efficiently.
"What if the countItems() method instead looped through all items to count them manually? How would the time complexity change?"