Challenge - 5 Problems
Swift Extensions Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of extension adding method to struct
What is the output of this Swift code that uses an extension to add a method to a struct?
Swift
struct Rectangle { var width: Double var height: Double } extension Rectangle { func area() -> Double { return width * height } } let rect = Rectangle(width: 3, height: 4) print(rect.area())
Attempts:
2 left
💡 Hint
Extensions add methods without changing original struct code.
✗ Incorrect
The extension adds the 'area' method to Rectangle. The method calculates width * height, so 3 * 4 = 12.0.
🧠 Conceptual
intermediate1:30remaining
Why extensions do not modify original type source
Why do Swift extensions add new capabilities without modifying the original type's source code?
Attempts:
2 left
💡 Hint
Think about how extensions are part of the same type but declared outside original code.
✗ Incorrect
Extensions add new members at compile time, extending the type's capabilities without changing the original source code file.
🔧 Debug
advanced2:00remaining
Why does this extension method cause a compile error?
Given this code, why does the extension method cause a compile error?
Swift
struct Circle { var radius: Double } extension Circle { mutating func doubleRadius() { radius *= 2 } } let c = Circle(radius: 5) c.doubleRadius()
Attempts:
2 left
💡 Hint
Check how 'let' and 'var' affect mutating methods.
✗ Incorrect
The variable 'c' is declared with 'let', making it immutable. Mutating methods require a mutable instance declared with 'var'.
📝 Syntax
advanced1:30remaining
Which extension syntax correctly adds a computed property?
Which option correctly adds a computed property 'isEven' to Int using an extension?
Attempts:
2 left
💡 Hint
Computed properties use 'var' without parentheses.
✗ Incorrect
Option D correctly defines a computed property 'isEven' with 'var' and no parentheses. Option D defines a method, not a property. Option D has invalid syntax for a property. Option D tries to assign a property directly, which is invalid in extensions.
🚀 Application
expert2:30remaining
How extensions enable protocol conformance without modifying original type
How can Swift extensions add protocol conformance to a type without modifying its original source code?
Attempts:
2 left
💡 Hint
Extensions can declare protocol adoption and implement methods.
✗ Incorrect
Extensions can declare that a type conforms to a protocol and implement the required methods, all without changing the original source code.