Protocol-oriented design helps you write clear and flexible code. It makes your programs easier to change and reuse.
Why protocol-oriented design matters in 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.
Drivable and a struct Car that follows it by implementing drive().protocol Drivable { func drive() } struct Car: Drivable { func drive() { print("Car is driving") } }
Flyable is a protocol for flying behavior, and Bird adopts it.protocol Flyable { func fly() } struct Bird: Flyable { func fly() { print("Bird is flying") } }
User must have an id string.protocol Identifiable { var id: String { get } } struct User: Identifiable { var id: String }
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.
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)
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.
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.