Challenge - 5 Problems
Swift Initializer Extension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of initializer added via extension
What is the output of this Swift code that adds an initializer via extension?
Swift
struct Point { var x: Int var y: Int } extension Point { init() { self.x = 0 self.y = 0 } } let p = Point() print("(\(p.x), \(p.y))")
Attempts:
2 left
💡 Hint
Think about what the extension initializer sets the properties to.
✗ Incorrect
The extension adds an initializer that sets x and y to 0, so the output is (0, 0).
❓ Predict Output
intermediate2:00remaining
Value of property after extension initializer
What is the value of the property 'name' after creating an instance using the extension initializer?
Swift
class Person { var name: String init(name: String) { self.name = name } } extension Person { convenience init() { self.init(name: "Unknown") } } let p = Person() print(p.name)
Attempts:
2 left
💡 Hint
Check what the convenience initializer passes to the designated initializer.
✗ Incorrect
The convenience initializer calls the designated initializer with "Unknown", so p.name is "Unknown".
🔧 Debug
advanced2:00remaining
Why does this extension initializer cause a compile error?
Consider this Swift code. Why does the extension initializer cause a compile error?
Swift
struct Rectangle { var width: Int var height: Int } extension Rectangle { init(area: Int) { self.width = area // Missing height initialization } }
Attempts:
2 left
💡 Hint
Check if all stored properties are initialized in the initializer.
✗ Incorrect
Swift requires all stored properties to be initialized before the initializer ends. Here, height is not initialized, causing a compile error.
📝 Syntax
advanced2:00remaining
Which extension initializer syntax is correct?
Which of the following extension initializers for struct Circle is syntactically correct?
Swift
struct Circle { var radius: Double } // Choose the correct extension initializer syntax:
Attempts:
2 left
💡 Hint
Remember that convenience initializers are only for classes, not structs.
✗ Incorrect
Structs cannot have convenience initializers, so options A and D are invalid. Also, self. is required to assign to properties, so C is invalid.
🚀 Application
expert2:00remaining
How many initializers does this class have after extension?
Given this Swift class and its extension, how many initializers does the class have in total?
Swift
class Vehicle { var wheels: Int init(wheels: Int) { self.wheels = wheels } } extension Vehicle { convenience init() { self.init(wheels: 4) } }
Attempts:
2 left
💡 Hint
Count both the original and extension initializers.
✗ Incorrect
The class has one designated initializer and one convenience initializer added by the extension, totaling 2 initializers.