📖 Scenario: You are creating a simple app that manages information about books. You want to add a new way to create book objects easily by adding an initializer through an extension.
🎯 Goal: Learn how to add a new initializer to an existing Book struct using an extension in Swift.
📋 What You'll Learn
Create a Book struct with two properties: title and author, both of type String.
Add an extension to Book that includes a new initializer which takes a single String parameter called combined.
The new initializer should split the combined string by a dash " - " and assign the first part to title and the second part to author.
Create a Book instance using the new initializer with the string "1984 - George Orwell".
Print the title and author of the created Book.
💡 Why This Matters
🌍 Real World
Adding initializers via extensions helps you add new ways to create objects without changing the original code. This is useful when working with libraries or when you want to keep your code organized.
💼 Career
Understanding how to extend existing types and add initializers is important for Swift developers working on apps that handle data parsing, user input, or need flexible object creation.
Progress0 / 4 steps
1
Create the Book struct
Create a struct called Book with two properties: title and author, both of type String.
Swift
Hint
Use struct Book { var title: String; var author: String } to define the structure.
2
Add an extension with a new initializer
Add an extension to Book that defines a new initializer init(combined: String). Inside it, split the combined string by " - " and assign the first part to title and the second part to author.
Swift
Hint
Use extension Book { init(combined: String) { ... } } and split(separator: "-") to separate the string.
3
Create a Book instance using the new initializer
Create a constant book using the new initializer with the string "1984 - George Orwell".
Swift
Hint
Create the book with let book = Book(combined: "1984 - George Orwell").
4
Print the book's title and author
Print the title and author of the book constant using two separate print statements.
Swift
Hint
Use print(book.title) and print(book.author) to show the values.
Practice
(1/5)
1. What is the main purpose of adding initializers via extension in Swift?
easy
A. To convert a class into a struct
B. To override existing initializers in the original type
C. To delete initializers from the original type
D. To add new ways to create instances without modifying the original type code
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 D
Quick Check:
Extensions add features = A [OK]
Hint: Extensions add, not change original initializers [OK]
2. Which of the following is the correct syntax to add a new initializer to a struct Point via extension?
easy
A. extension Point { init(x: Int, y: Int) { self.x = x; self.y = y } }
B. extension Point { func init(x: Int, y: Int) { self.x = x; self.y = y } }
C. extension Point { init Point(x: Int, y: Int) { self.x = x; self.y = y } }
D. extension Point { initializer(x: Int, y: Int) { self.x = x; self.y = y } }
Solution
Step 1: Recall initializer syntax in extensions
Initializers use the keyword init without a function keyword.
Step 2: Check each option's syntax
extension Point { init(x: Int, y: Int) { self.x = x; self.y = y } } correctly uses init with parameters and assigns properties. Others misuse keywords like func, add extra words, or wrong keywords.
Final Answer:
extension Point { init(x: Int, y: Int) { self.x = x; self.y = y } } -> Option A
Quick Check:
Use init keyword only for initializers [OK]
Hint: Initializers use 'init', not 'func' or 'initializer' [OK]
Common Mistakes:
Using 'func' instead of 'init' for initializers
Adding extra words like 'initializer' or type name after 'init'
Incorrect punctuation or missing braces
3. Given the code below, what will be printed?
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)
medium
A. 5 0
B. 0 0
C. 5 5
D. Compilation error
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
Creating square with size: 5 sets width and height to 5. Printing outputs "5 5".
Final Answer:
5 5 -> Option C
Quick Check:
Extension init sets both properties = 5 5 [OK]
Hint: Extension init sets all properties explicitly [OK]
Common Mistakes:
Assuming default values instead of assigned ones
Expecting compilation error due to missing original initializer
Confusing property values after init
4. What is wrong with this extension adding an initializer to a class Car?
class Car {
var model: String
init(model: String) {
self.model = model
}
}
extension Car {
init() {
model = "Unknown"
}
}
medium
A. Missing call to designated initializer in extension initializer
B. Cannot add initializers to classes via extensions
C. Property model is not declared
D. Extension initializer must have parameters
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 sets model directly but does not call self.init(model:), violating the rule.
Final Answer:
Missing call to designated initializer in extension initializer -> Option A
Quick Check:
Class extension init must call designated init [OK]
Hint: Class extension init must call self.init(...) [OK]
Common Mistakes:
Forgetting to call designated initializer in class extension
Thinking extensions can't add initializers to classes
Assuming properties auto-initialize without init call
5. You want to add an initializer to a struct 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?
hard
A. extension User {
init(data: [String: String]) {
self.name = data["name"]!
self.email = data["email"]!
}
}
B. extension User {
init(data: [String: String]) {
self.name = data["name"] ?? ""
self.email = data["email"] ?? ""
}
}
C. extension User {
init(data: [String: String]) {
self.name = data["name"]
self.email = data["email"]
}
}
D. extension User {
init(data: [String: String]) {
name = data["name"] ?? ""
email = data["email"] ?? ""
}
}
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 uses self.name and self.email with safe unwrapping. extension User {
init(data: [String: String]) {
name = data["name"] ?? ""
email = data["email"] ?? ""
}
} misses self. which is required in initializers.