Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Protocol-oriented Programming in Swift
Written by Team Kodeco

Protocol-Oriented Programming (POP) is a programming paradigm that emphasizes the use of protocols to define the blueprint of an object’s behavior, rather than inheritance. POP is a powerful technique for creating flexible and maintainable code in Swift.

Here’s an example of a protocol called Movable that defines the blueprint for an object that can move.

protocol Movable {
  func move()
}

extension Movable {
  func move() {
    print("Moving")
  }
}

You can then create a struct that conforms to the Movable protocol and implements the move() method.

struct Car: Movable {}

You can also create a class that conforms to the Movable protocol.

class Train: Movable {}

You can then create an array of Movable objects and call the move() method on each one, without knowing the specific type of the object:

let vehicles: [Movable] = [Car(), Train()]
for vehicle in vehicles {
  vehicle.move()
}
// Output: "Moving"
// Output: "Moving"

An analogy for Protocol-Oriented Programming would be a set of blueprints for building a house. The blueprints define the layout, the number of rooms and the plumbing and electrical systems. The builder can then build the house with these blueprints, but use different materials and decor to make it unique.

By using protocol-oriented programming, you can create code that is more flexible and maintainable. You can define the blueprint of an object’s behavior once in a protocol and then use that protocol to create multiple structs and classes that conform to it, each using the default implementation from the protocol. This allows you to write more reusable and testable code and makes it easier to add new functionality in the future.

© 2024 Kodeco Inc.