0
0
Swiftprogramming~5 mins

Protocol extensions with default implementations in Swift

Choose your learning style9 modes available
Introduction

Protocol extensions let you add common behavior to many types at once. Default implementations mean you don't have to write the same code again and again.

When you want many types to share the same behavior without repeating code.
When you want to add new features to a protocol without breaking existing code.
When you want to provide a simple default that most types can use but still allow customization.
When you want to keep your code clean and easy to maintain by avoiding duplication.
Syntax
Swift
protocol SomeProtocol {
    func doSomething()
}

extension SomeProtocol {
    func doSomething() {
        print("Default action")
    }
}

The extension adds default code for the protocol's methods.

Types that adopt the protocol can use the default or provide their own version.

Examples
Here, greet() has a default message "Hello!" for all types that adopt Greetable.
Swift
protocol Greetable {
    func greet()
}

extension Greetable {
    func greet() {
        print("Hello!")
    }
}
Person provides its own greet(), but Robot uses the default from the extension.
Swift
struct Person: Greetable {
    func greet() {
        print("Hi, I'm a person.")
    }
}

struct Robot: Greetable {}
Sample Program

This program shows a protocol Vehicle with a default startEngine() method. Car provides its own version, but Bike uses the default.

Swift
protocol Vehicle {
    func startEngine()
}

extension Vehicle {
    func startEngine() {
        print("Starting engine with default method.")
    }
}

struct Car: Vehicle {
    func startEngine() {
        print("Car engine started.")
    }
}

struct Bike: Vehicle {}

let myCar = Car()
myCar.startEngine()

let myBike = Bike()
myBike.startEngine()
OutputSuccess
Important Notes

If a type provides its own method, it overrides the default from the extension.

Default implementations help keep your code DRY (Don't Repeat Yourself).

Summary

Protocol extensions let you add default behavior to protocols.

Types can use the default or provide their own implementation.

This makes your code cleaner and easier to maintain.