0
0
Swiftprogramming~5 mins

Protocol composition in Swift

Choose your learning style9 modes available
Introduction

Protocol composition lets you combine multiple protocols into one requirement. It helps you say: "I want something that follows these rules together."

When a function needs a parameter that follows more than one protocol.
When you want to group behaviors without creating a new protocol.
When you want to write flexible code that works with different types sharing multiple features.
Syntax
Swift
func exampleFunction(param: ProtocolA & ProtocolB) {
    // code here
}

Use the & symbol to combine protocols.

The combined type must conform to all listed protocols.

Examples
This function accepts any object that can both drive and fly.
Swift
protocol Drivable {
    func drive()
}

protocol Flyable {
    func fly()
}

func travel(vehicle: Drivable & Flyable) {
    vehicle.drive()
    vehicle.fly()
}
This function requires a 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 Singer. The Artist struct follows both. The perform function uses protocol composition to accept anything that can paint and sing. It calls both methods.

Swift
protocol Painter {
    func paint()
}

protocol Singer {
    func sing()
}

struct Artist: Painter, Singer {
    func paint() {
        print("Painting a beautiful picture.")
    }
    func sing() {
        print("Singing a lovely song.")
    }
}

func perform(show: Painter & Singer) {
    show.paint()
    show.sing()
}

let artist = Artist()
perform(show: artist)
OutputSuccess
Important Notes

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

It helps keep code flexible and reusable.

Summary

Protocol composition combines multiple protocols using &.

It lets you require multiple behaviors at once.

Use it to write flexible and clear code.