SwiftMidMCQ
What is a protocol extension and why is it powerful?
Test your knowledge:
Explanation & Code
Answer: Protocol extensions let you add default implementations to protocol methods, so conforming types get behavior for free without inheriting from a base class.
Code Example:
protocol Greetable {
var name: String { get }
func greet() -> String
}
extension Greetable {
func greet() -> String {
return "Hello, \(name)!"
}
}
struct User: Greetable {
var name: String
// greet() is provided for free by the extension
}
let user = User(name: "Mia")
print(user.greet()) // "Hello, Mia!"
Key Points:
- Enables composition over inheritance
- Multiple protocols can be adopted (vs single class inheritance)
- Constrained extensions let you add methods only for specific types
Rate your understanding: