Default Implementations in Extensions
Provide shared behavior via protocol extensions.
The Problem
Protocols declare requirements but provide no behavior. If every conforming type had to repeat the same logic, you would duplicate code. Protocol extensions solve this by supplying default implementations.
protocol Greeter {
func greet() -> String
}Adding a Default
An extension on the protocol can implement a requirement. Conforming types get that behavior for free unless they override it.
protocol Greeter { func greet() -> String }
extension Greeter {
func greet() -> String { "Hello!" }
}
struct Robot: Greeter {}
print(Robot().greet())All lessons in this course
- Protocols as Contracts
- Default Implementations in Extensions
- Protocol Composition
- Conditional Conformance