0
0
Swiftprogramming~5 mins

Protocol composition in practice in Swift

Choose your learning style9 modes available
Introduction

Protocol composition lets you combine multiple protocols into one requirement. This helps you write flexible and clear code by saying "I need something that does all these things."

When a function needs an argument that meets several different behaviors at once.
When you want to group multiple protocol requirements without creating a new protocol.
When you want to write code that works with objects that share multiple capabilities.
When you want to keep your code simple and avoid deep inheritance chains.
Syntax
Swift
func exampleFunction(param: ProtocolA & ProtocolB) {
    // code using param
}

Use the ampersand (&) to combine protocols.

The parameter must conform to all listed protocols.

Examples
This function requires a vehicle that can both drive and refuel.
Swift
protocol Drivable {
    func drive()
}

protocol Refuelable {
    func refuel()
}

func operate(vehicle: Drivable & Refuelable) {
    vehicle.drive()
    vehicle.refuel()
}
This function works with any document that can be read and written.
Swift
protocol Readable {
    func read()
}

protocol Writable {
    func write()
}

func process(document: Readable & Writable) {
    document.read()
    document.write()
}
Sample Program

This program defines two protocols, Painter and Cleaner. The Robot struct conforms to both. The function startWork requires a worker that can paint and clean. We create a Robot and pass it to startWork, so it paints and cleans.

Swift
protocol Painter {
    func paint()
}

protocol Cleaner {
    func clean()
}

struct Robot: Painter, Cleaner {
    func paint() {
        print("Painting the wall")
    }
    func clean() {
        print("Cleaning the floor")
    }
}

func startWork(worker: Painter & Cleaner) {
    worker.paint()
    worker.clean()
}

let robot = Robot()
startWork(worker: robot)
OutputSuccess
Important Notes

Protocol composition is a way to require multiple behaviors without making a new protocol.

You can use protocol composition anywhere a type is expected, like function parameters or variables.

It helps keep your code flexible and easy to change later.

Summary

Protocol composition combines multiple protocols using &.

It lets you require multiple behaviors at once without new protocols.

Use it to write clear, flexible, and reusable code.