Initializers and designated init in Swift - Time & Space Complexity
When we create objects in Swift, initializers set up their starting state. Understanding how long this setup takes helps us write faster programs.
We want to know how the time to create an object changes as we add more properties or complexity.
Analyze the time complexity of the following initializer code.
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
This code sets up a Person object with a name and age using a designated initializer.
Look for repeated steps or loops in the initializer.
- Primary operation: Assigning values to properties.
- How many times: Each property is assigned once per object creation.
As we add more properties, the number of assignments grows.
| Input Size (number of properties) | Approx. Operations |
|---|---|
| 2 | 2 assignments |
| 10 | 10 assignments |
| 100 | 100 assignments |
Pattern observation: The time grows directly with the number of properties to set.
Time Complexity: O(n)
This means the time to initialize grows linearly with the number of properties.
[X] Wrong: "Initializers always take the same time no matter how many properties there are."
[OK] Correct: Each property needs to be set, so more properties mean more work and more time.
Understanding how initializers work and their time cost shows you know how object setup affects performance, a useful skill in many coding tasks.
"What if the initializer called another initializer inside it? How would that affect the time complexity?"