Convenience initializers in Swift - Time & Space Complexity
When using convenience initializers in Swift, it's helpful to know how the time to create an object changes as input grows.
We want to see how the number of steps to initialize an object scales with input size.
Analyze the time complexity of the following code snippet.
class NumberList {
var numbers: [Int]
init(numbers: [Int]) {
self.numbers = numbers
}
convenience init(count: Int) {
var temp = [Int]()
for i in 1...count {
temp.append(i)
}
self.init(numbers: temp)
}
}
This code creates a list of numbers either from an existing array or by building one from 1 to count.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that appends numbers from 1 to count.
- How many times: Exactly count times, once for each number.
As the count grows, the loop runs more times, adding one number each time.
| Input Size (count) | Approx. Operations |
|---|---|
| 10 | 10 appends |
| 100 | 100 appends |
| 1000 | 1000 appends |
Pattern observation: The work grows directly with the input size; doubling count doubles the steps.
Time Complexity: O(n)
This means the time to initialize grows linearly with the number of items you want to create.
[X] Wrong: "Convenience initializers always run instantly regardless of input size."
[OK] Correct: Because if the initializer builds or processes data in a loop, the time depends on how much data it handles.
Understanding how initializers scale helps you write efficient code and explain your design choices clearly in interviews.
"What if the convenience initializer used recursion instead of a loop? How would the time complexity change?"