Adding initializers via extension in Swift - Time & Space Complexity
When we add initializers using extensions in Swift, it is important to understand how this affects the time it takes to create objects.
We want to know how the time to initialize grows as we create more instances.
Analyze the time complexity of the following code snippet.
struct Point {
var x: Int
var y: Int
}
extension Point {
init(value: Int) {
self.x = value
self.y = value
}
}
let points = (1...n).map { Point(value: $0) }
This code adds a new initializer to the Point struct using an extension, then creates an array of Points using that initializer.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating each Point instance using the new initializer.
- How many times: The initializer runs once for each number from 1 to n.
Each new Point is created one after another, so the total time grows directly with how many Points we make.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 initializations |
| 100 | 100 initializations |
| 1000 | 1000 initializations |
Pattern observation: The time increases evenly as we add more Points.
Time Complexity: O(n)
This means the time to create all Points grows in a straight line with the number of Points.
[X] Wrong: "Adding an initializer via extension makes object creation slower in a way that grows faster than the number of objects."
[OK] Correct: The initializer code runs once per object, so the total time grows directly with the number of objects, not faster.
Understanding how adding initializers affects creation time helps you explain how your code scales when making many objects, a useful skill in real projects.
"What if the initializer did some extra work like looping inside it? How would the time complexity change?"