How does Protocol-Oriented Programming (POP) differ from classic class-based OOP?
Explanation & Code
Answer:
Classic OOP centers on classes and inheritance hierarchies — behavior is shared by subclassing a base class. Swift instead favors Protocol-Oriented Programming: define behavior as protocols, share default implementations via protocol extensions, and let both structs and classes adopt them. This sidesteps single-inheritance limits and the fragile-base-class problem, and works naturally with value types.
protocol Flyable {
func fly()
}
extension Flyable {
func fly() { print("Flapping wings") } // default implementation, no base class needed
}
struct Sparrow: Flyable {} // gets fly() for free
struct Airplane: Flyable {
func fly() { print("Engines roaring") } // overrides the default
}
A struct can adopt ten protocols and get default behavior from each — something a single-inheritance class hierarchy can't express cleanly. This is also why Apple frameworks (e.g., Equatable, Collection, Identifiable) lean heavily on protocols rather than base classes.
Rate your understanding: