0
0
Swiftprogramming~5 mins

Why protocol-oriented design matters in Swift

Choose your learning style9 modes available
Introduction

Protocol-oriented design helps you write clear and flexible code. It makes your programs easier to change and reuse.

When you want different parts of your app to share common behavior without repeating code.
When you need to swap or change parts of your program easily without breaking everything.
When you want to write tests for your code by using simple, replaceable pieces.
When you want to organize your code by what it does, not just by what it is.
When you want to avoid complex inheritance and keep your code simple and clear.
Syntax
Swift
protocol SomeProtocol {
    func doSomething()
}

struct SomeStruct: SomeProtocol {
    func doSomething() {
        print("Doing something")
    }
}

A protocol defines a set of methods or properties that a type must have.

Types like struct, class, or enum can adopt protocols to promise they implement those methods.

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

struct Car: Drivable {
    func drive() {
        print("Car is driving")
    }
}
Here, Flyable is a protocol for flying behavior, and Bird adopts it.
Swift
protocol Flyable {
    func fly()
}

struct Bird: Flyable {
    func fly() {
        print("Bird is flying")
    }
}
This shows a protocol with a property requirement. User must have an id string.
Swift
protocol Identifiable {
    var id: String { get }
}

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

This program shows how two different types, Person and Robot, can both greet because they follow the Greetable protocol. The function sayHello works with any Greetable type.

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, as long as they follow the same rules.

Using protocols helps avoid repeating code and makes your app easier to update later.

Protocol-oriented design is a key idea in Swift to build flexible and clean programs.

Summary

Protocols define shared behavior that many types can use.

Protocol-oriented design helps make code reusable and easy to change.

It encourages thinking about what things do, not just what they are.