Generic function declaration in Swift - Time & Space Complexity
We want to understand how the time it takes to run a generic function changes as the input size grows.
Specifically, we ask: how does the function's work increase when we give it more data?
Analyze the time complexity of the following code snippet.
func printElements(items: [T]) {
for item in items {
print(item)
}
}
let numbers = [1, 2, 3, 4, 5]
printElements(items: numbers)
This function takes an array of any type and prints each element one by one.
- Primary operation: Looping through each element in the array.
- How many times: Once for every item in the input array.
As the number of items grows, the function prints more elements, so it takes more time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print actions |
| 100 | 100 print actions |
| 1000 | 1000 print actions |
Pattern observation: The work grows directly with the number of items; doubling items doubles the work.
Time Complexity: O(n)
This means the time to run the function grows in a straight line with the number of items.
[X] Wrong: "Generic functions are slower because they handle many types."
[OK] Correct: The generic part only affects type flexibility, not how many times the loop runs. The time depends on input size, not type.
Understanding how generic functions scale helps you explain your code's efficiency clearly and confidently in real situations.
"What if we changed the function to print pairs of items instead of single items? How would the time complexity change?"