How do I create protocol extensions and default implementations in Swift?

In Swift, you can define protocol extensions to provide default implementations for the methods and properties defined in a protocol. This feature enhances flexibility and code reuse by allowing types conforming to the protocol to leverage these default behaviors while also enabling them to override when necessary.

Example of Protocol Extensions and Default Implementations

protocol Drawable {
        func draw()
    }

    extension Drawable {
        func draw() {
            print("Drawing a default shape.")
        }
    }

    struct Circle: Drawable {
        func draw() {
            print("Drawing a Circle.")
        }
    }

    struct Square: Drawable {} // Uses default implementation

    let myCircle = Circle()
    myCircle.draw()  // Outputs: Drawing a Circle.

    let mySquare = Square()
    mySquare.draw()  // Outputs: Drawing a default shape.
    

In this example, we define a protocol called Drawable with a method draw(). We then provide a default implementation of draw() in a protocol extension. The Circle struct provides its own implementation, while the Square struct uses the default.


Swift Protocol Extensions Default Implementations Swift Programming Code Reuse Protocols in Swift