Introduction
Protocol extensions let you add common behavior to many types at once, so you don't have to write the same code again and again.
protocol ProtocolName { // protocol requirements } extension ProtocolName { // shared behavior (default implementations) }
protocol Greetable { func greet() } extension Greetable { func greet() { print("Hello!") } }
protocol Describable { var description: String { get } } extension Describable { var description: String { return "This is a describable object." } }
protocol Vehicle { func startEngine() } extension Vehicle { func startEngine() { print("Engine started.") } } struct Car: Vehicle { // No need to write startEngine() here } struct Motorcycle: Vehicle { func startEngine() { print("Motorcycle engine started with a roar!") } } let myCar = Car() myCar.startEngine() // Uses default implementation let myBike = Motorcycle() myBike.startEngine() // Uses custom implementation
protocol extensions in Swift?greet() to a protocol Greeter using an extension?extension ProtocolName { func method() { ... } }.extension Greeter { func greet() { ... } }. Others misuse protocol or extension syntax.protocol Vehicle {
func start()
}
extension Vehicle {
func start() {
print("Starting vehicle")
}
}
struct Car: Vehicle {}
let myCar = Car()
myCar.start()protocol Speaker {
func speak()
}
extension Speaker {
func speak() {
print("Speaking")
}
}
struct Person: Speaker {
func speak() {
print("Hello")
}
}
let p = Person()
p.speak()describe() to multiple unrelated types Cat and Dog without repeating code. Which approach using protocol extensions is best?Pass the test and this pattern moves unknown