What if you could add new ways to create objects without ever touching the original code?
Why Adding initializers via extension in Swift? - Purpose & Use Cases
Imagine you have a Swift struct or class, and you want to create new ways to make instances of it. Without extensions, you have to change the original code every time you want a new initializer.
This manual way is slow and risky. Changing original code can cause bugs, and if the code is from a library, you can't change it at all. You end up repeating code or making messy workarounds.
Adding initializers via extension lets you add new ways to create instances without touching the original code. It keeps your code clean, safe, and flexible.
struct Person {
var name: String
var age: Int
init(name: String) {
self.name = name
self.age = 0
}
}struct Person {
var name: String
var age: Int
}
extension Person {
init(name: String) {
self.init(name: name, age: 0)
}
}You can easily add new initializers anytime, even for types you don't own, making your code more powerful and adaptable.
Suppose you use a library with a Date type. You want to create a Date from a string. You can add an initializer in an extension to do this without changing the library code.
Adding initializers via extension avoids changing original code.
It keeps your code clean and safe from bugs.
It allows flexible ways to create instances anytime.
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
