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?"
Practice
extension in Swift?Solution
Step 1: Understand what extensions do
Extensions allow adding new features to existing types without changing their original code.Step 2: Focus on initializers added via extensions
Adding initializers via extension means creating new ways to make instances without touching the original type's code.Final Answer:
To add new ways to create instances without modifying the original type code -> Option DQuick Check:
Extensions add features = A [OK]
- Thinking extensions override existing initializers
- Believing extensions remove initializers
- Confusing extensions with type conversion
Point via extension?Solution
Step 1: Recall initializer syntax in extensions
Initializers use the keywordinitwithout a function keyword.Step 2: Check each option's syntax
extension Point { init(x: Int, y: Int) { self.x = x; self.y = y } } correctly usesinitwith parameters and assigns properties. Others misuse keywords likefunc, add extra words, or wrong keywords.Final Answer:
extension Point { init(x: Int, y: Int) { self.x = x; self.y = y } } -> Option AQuick Check:
Useinitkeyword only for initializers [OK]
- Using 'func' instead of 'init' for initializers
- Adding extra words like 'initializer' or type name after 'init'
- Incorrect punctuation or missing braces
struct Rectangle {
var width: Int
var height: Int
}
extension Rectangle {
init(size: Int) {
self.width = size
self.height = size
}
}
let square = Rectangle(size: 5)
print(square.width, square.height)Solution
Step 1: Understand the extension initializer
The extension adds an initializer that sets both width and height to the same size value.Step 2: Analyze the instance creation and print
Creatingsquarewithsize: 5sets width and height to 5. Printing outputs "5 5".Final Answer:
5 5 -> Option CQuick Check:
Extension init sets both properties = 5 5 [OK]
- Assuming default values instead of assigned ones
- Expecting compilation error due to missing original initializer
- Confusing property values after init
Car?
class Car {
var model: String
init(model: String) {
self.model = model
}
}
extension Car {
init() {
model = "Unknown"
}
}Solution
Step 1: Recall rules for class initializers in extensions
When adding a convenience initializer in an extension, it must call a designated initializer of the class.Step 2: Check the extension initializer code
The extension initializer setsmodeldirectly but does not callself.init(model:), violating the rule.Final Answer:
Missing call to designated initializer in extension initializer -> Option AQuick Check:
Class extension init must call designated init [OK]
- Forgetting to call designated initializer in class extension
- Thinking extensions can't add initializers to classes
- Assuming properties auto-initialize without init call
User via extension that accepts a dictionary [String: String] and sets name and email. Which code correctly implements this, handling missing keys by setting empty strings?Solution
Step 1: Understand safe unwrapping of dictionary values
Using?? ""provides a default empty string if the key is missing, avoiding runtime errors.Step 2: Check property assignment and self usage
extension User { init(data: [String: String]) { self.name = data["name"] ?? "" self.email = data["email"] ?? "" } } correctly usesself.nameandself.emailwith safe unwrapping. extension User { init(data: [String: String]) { name = data["name"] ?? "" email = data["email"] ?? "" } } missesself.which is required in initializers.Final Answer:
extension User { init(data: [String: String]) { self.name = data["name"] ?? "" self.email = data["email"] ?? "" } } -> Option BQuick Check:
Use self and safe default values in init [OK]
- Force unwrapping dictionary values causing crashes
- Omitting 'self.' when assigning properties in init
- Not providing default values for missing keys
Ready to prove it?
Pass the test and this pattern moves unknown
