Protocol Extensions
A protocol extension lets you write actual code once, right on the checklist itself, so every type that conforms automatically gets that behavior for free.
Providing a Default Implementation
A protocol extension can implement a method directly, so any conforming type gets that behavior automatically without writing it themselves.
Example: Providing a Default Implementation
protocol Greetable {
var name: String { get }
}
extension Greetable {
func greet() -> String {
return "Hello, \(name)!"
}
}
struct Visitor: Greetable {
var name: String
}
let visitor = Visitor(name: "Sam")
print(visitor.greet())
Login to try C/C++/Java/PHP code in the editor
Overriding a Default Implementation
A conforming type can still provide its own implementation of a method that a protocol extension already defines, which takes priority for that type.
Example: Overriding a Default Implementation
protocol Greetable {
var name: String { get }
}
extension Greetable {
func greet() -> String {
return "Hello, \(name)!"
}
}
struct Robot: Greetable {
var name: String
func greet() -> String {
return "BEEP \(name) BOOP"
}
}
let robot = Robot(name: "Unit1")
print(robot.greet())
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Assuming a protocol extension's default implementation always runs; a conforming type can still override it with its own implementation.
- Forgetting that protocol extensions cannot add new required members -- they only provide default implementations or entirely new convenience methods.
- Adding stored properties in a protocol extension, which is not allowed; only computed properties and methods can be added.
Chapter Summary
- A protocol extension provides a default implementation for a method or computed property.
- Any conforming type automatically gets the default unless it provides its own implementation.
- Extensions cannot add stored properties or new required members to a protocol.
- This pattern reduces repeated boilerplate across many conforming types.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: