Recall & Review
beginner
What is an extension in Swift?
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?
✗ 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?
✗ 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?
✗ 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?
✗ 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?
✗ 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.