0
0
Swiftprogramming~5 mins

Protocol extensions for shared behavior in Swift

Choose your learning style9 modes available
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.
When you want many different types to share the same function without repeating code.
When you want to add default behavior to a protocol so all types that follow it get that behavior automatically.
When you want to keep your code clean and organized by grouping shared functions in one place.
When you want to add helper methods to a protocol without changing each type that uses it.
Syntax
Swift
protocol ProtocolName {
    // protocol requirements
}

extension ProtocolName {
    // shared behavior (default implementations)
}
You write the protocol first with the required methods or properties.
Then you add an extension to the protocol to provide default implementations.
Examples
Here, any type that follows Greetable will get a default greet() method that prints "Hello!".
Swift
protocol Greetable {
    func greet()
}

extension Greetable {
    func greet() {
        print("Hello!")
    }
}
This adds a default description property to all Describable types.
Swift
protocol Describable {
    var description: String { get }
}

extension Describable {
    var description: String {
        return "This is a describable object."
    }
}
Sample Program
Car uses the default startEngine() from the protocol extension. Motorcycle provides its own version.
Swift
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
OutputSuccess
Important Notes
If a type provides its own implementation, it overrides the protocol extension's default.
Protocol extensions cannot add stored properties, only methods or computed properties.
Use protocol extensions to keep your code DRY (Don't Repeat Yourself).
Summary
Protocol extensions let you add shared behavior to many types easily.
They provide default implementations for protocol methods or properties.
Types can override these defaults if needed.