An extension in Swift adds new functionality to an existing class, struct, enum, or protocol without modifying the original source code.
Click to reveal answer
beginner
Can you add initializers to a struct using an extension in Swift?
Yes, you can add new initializers to a struct using an extension, allowing you to create instances in new ways without changing the original struct definition.
Click to reveal answer
intermediate
Why can't you add designated initializers to a class via extension in Swift?
Swift does not allow adding designated initializers to classes via extensions because it could break the class's initialization rules and safety guarantees.
Click to reveal answer
intermediate
What is the difference between a convenience initializer and a designated initializer in Swift?
A designated initializer fully initializes all properties and calls a superclass initializer. A convenience initializer calls another initializer in the same class and provides a shortcut for common initialization.
Click to reveal answer
beginner
Show a simple example of adding an initializer to a struct using an extension in Swift.
struct Point { var x: Int; var y: Int }
extension Point {
init(value: Int) {
self.x = value
self.y = value
}
}
// Now you can create Point(value: 5) to set both x and y to 5.
Click to reveal answer
Which of the following can you add via extension in Swift?
ANew initializers to a struct
BDesignated initializers to a class
CStored properties
DDeinitializers
✗ Incorrect
You can add new initializers to structs via extensions, but not designated initializers to classes. Stored properties and deinitializers cannot be added via extensions.
What keyword is used to define an extension in Swift?
Aadd
Bextend
Cextension
Dinclude
✗ Incorrect
The keyword 'extension' is used to add new functionality to existing types in Swift.
Why can't you add stored properties in an extension?
ABecause stored properties are deprecated
BBecause extensions can only add computed properties and methods
CBecause Swift does not support extensions
DBecause stored properties require memory allocation which extensions can't do
✗ Incorrect
Extensions cannot add stored properties because they require additional memory allocation, which is not allowed in extensions.
Which initializer type can you add to a class via extension?
AConvenience initializer
BDesignated initializer
CDeinitializer
DStored property initializer
✗ Incorrect
You can add convenience initializers to classes via extensions, but not designated initializers.
What happens if you add an initializer in an extension that duplicates an existing initializer?
AThe new initializer overrides the old one
BCompilation error due to duplicate initializers
CBoth initializers coexist without issues
DThe program crashes at runtime
✗ Incorrect
Swift does not allow duplicate initializers with the same signature; this causes a compilation error.
Explain how to add an initializer to a struct using an extension in Swift and why this might be useful.
Think about how extensions let you add new ways to create instances without changing the original struct.
You got /4 concepts.
Describe the limitations of adding initializers via extensions for classes in Swift.
Consider Swift's rules about class initialization and safety.
You got /3 concepts.
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.