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?"
Practice
Solution
Step 1: Understand what initializers do
Initializers set starting values for new objects to ensure they are ready to use.Step 2: Identify the role of designated initializers
Designated initializers fully initialize all properties of a class, making the object safe and complete.Final Answer:
To fully initialize all properties of a class before use -> Option AQuick Check:
Designated initializer = full property initialization [OK]
- Confusing designated init with convenience init
- Thinking initializers copy objects
- Mixing initialization with deallocation
Solution
Step 1: Recall Swift initializer syntax
In Swift, initializers use the keywordinitwithout a return type or func keyword.Step 2: Identify the correct syntax
The correct syntax isinit() { }. Other options use incorrect keywords or syntax.Final Answer:
init() { } -> Option BQuick Check:
Swift designated init syntax = init() { } [OK]
- Using 'func' keyword with init
- Using 'constructor' or 'initialize' instead of 'init'
- Adding return types to init
class Person {
var name: String
var age: Int
init(name: String) {
self.name = name
self.age = 0
}
}
What will be the value of age after creating let p = Person(name: "Anna")?Solution
Step 1: Analyze the initializer code
The initializer setsself.name = nameand explicitly setsself.age = 0.Step 2: Determine the value of age after initialization
Sinceageis set to 0 inside the initializer, the new object will haveage = 0.Final Answer:
0 -> Option DQuick Check:
Explicit age assignment = 0 [OK]
- Assuming age is nil because not passed as parameter
- Thinking age is uninitialized or undefined
- Confusing name with age value
class Car {
var model: String
var year: Int
init(model: String) {
model = model
year = 2020
}
}Solution
Step 1: Check property assignments in initializer
The code assignsmodel = modelandyear = 2020withoutself., so it assigns parameters to themselves, not properties.Step 2: Understand correct property initialization
Properties must be assigned withself.model = modelandself.year = 2020to set the instance variables.Final Answer:
Properties are not initialized using self keyword -> Option CQuick Check:
Use self.property = value to initialize [OK]
- Forgetting self. causes no property assignment
- Adding return type to init
- Thinking inheritance affects property assignment
Book with properties title (String) and pages (Int). The designated initializer should allow setting both properties, but if pages is not provided, it defaults to 100. Which is the best way to write this initializer?Solution
Step 1: Understand default parameter values in Swift
Swift allows default values in parameters, sopages: Int = 100means pages defaults to 100 if not passed.Step 2: Check initializer completeness and safety
The initializerinit(title: String, pages: Int = 100) { self.title = title; self.pages = pages }sets both properties properly and safely with a default value. The version with only atitleparameter cannot setpagesexplicitly. The version taking both parameters but only assigningtitlemisses thepagesassignment. The version using an optionalInt?for pages with force unwrap is unsafe.Final Answer:
init(title: String, pages: Int = 100) { self.title = title; self.pages = pages } -> Option AQuick Check:
Default parameter = safe default value [OK]
- Forgetting to assign all properties
- Using force unwrap (!) unsafely
- Not providing default value in parameter
Ready to prove it?
Pass the test and this pattern moves unknown
