0
0
Swiftprogramming~5 mins

Why protocol-oriented programming matters in Swift

Choose your learning style9 modes available
Introduction

Protocol-oriented programming helps you write clear and reusable code by focusing on what things can do, not what they are.

When you want to share common behavior across different types without using inheritance.
When you want to write flexible code that works with many kinds of objects.
When you want to make your code easier to test and maintain.
When you want to define clear rules for what a type should do.
When you want to avoid tight coupling between parts of your code.
Syntax
Swift
protocol SomeProtocol {
    func doSomething()
}

struct SomeStruct: SomeProtocol {
    func doSomething() {
        // implementation
    }
}

A protocol defines a blueprint of methods or properties.

Types like structs, classes, or enums can adopt protocols to promise they implement those methods.

Examples
This example shows a protocol Drivable and a struct Car that follows it.
Swift
protocol Drivable {
    func drive()
}

struct Car: Drivable {
    func drive() {
        print("Car is driving")
    }
}
Here, the protocol requires a property id. The struct User provides it.
Swift
protocol Identifiable {
    var id: String { get }
}

struct User: Identifiable {
    var id: String
}
Sample Program

This program shows how different types can follow the same protocol and be used interchangeably.

Swift
protocol Greetable {
    func greet()
}

struct Person: Greetable {
    var name: String
    func greet() {
        print("Hello, my name is \(name)")
    }
}

struct Robot: Greetable {
    func greet() {
        print("Beep boop, I am a robot")
    }
}

func sayHello(to greeter: Greetable) {
    greeter.greet()
}

let alice = Person(name: "Alice")
let bot = Robot()

sayHello(to: alice)
sayHello(to: bot)
OutputSuccess
Important Notes

Protocols let you write code that works with many types, making your code flexible.

Using protocols can reduce the need for complex class inheritance.

Swift's standard library uses protocols a lot, so learning them helps you understand Swift better.

Summary

Protocols define what actions or properties a type must have.

Protocol-oriented programming focuses on behavior, not just data.

This approach makes your code easier to reuse and maintain.