Typealias for custom naming in Swift - Time & Space Complexity
Let's see how using typealias affects the time it takes for a program to run.
We want to know if giving a new name to a type changes how fast the code works.
Analyze the time complexity of the following code snippet.
typealias Age = Int
func printAges(ages: [Age]) {
for age in ages {
print(age)
}
}
let agesList: [Age] = [21, 35, 42, 18]
printAges(ages: agesList)
This code uses typealias to rename Int as Age. It then prints each age in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array
agesto print each item. - How many times: Once for each element in the array.
As the list of ages gets bigger, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of ages.
[X] Wrong: "Using typealias makes the code slower because it adds extra steps."
[OK] Correct: typealias only gives a new name to a type and does not change how the code runs or how fast it is.
Understanding that typealias is just a naming tool helps you focus on what really affects performance in your code.
"What if the function printed each age twice inside the loop? How would the time complexity change?"