Explain the concept of 'Protocol-Oriented Programming' in Swift and how it compares to traditional 'Object-Oriented Programming'.

Instruction: Provide a detailed explanation of Protocol-Oriented Programming (POP) in Swift, including its benefits and when it should be used over Object-Oriented Programming (OOP). Include examples to illustrate your points.

Context: This question assesses the candidate's understanding of advanced Swift programming paradigms. By comparing POP with OOP, the candidate demonstrates their grasp of Swift's unique features and how they can be applied to write more flexible, reusable, and efficient code. Examples will help illustrate the candidate's practical experience with these concepts.

Updated

Official answer

Protocol-oriented design defines required behavior independently of a class hierarchy. Structs, enums and classes can conform, while protocol extensions provide reusable behavior and generics express constraints. Object-oriented design often shares implementation through classes and inheritance. They can be combined: a class can conform to several protocols while inheriting from one superclass.

This complete example shares a derived behavior without forcing the two models into an inheritance tree:

protocol AreaProviding {
    var area: Double { get }
}
extension AreaProviding {
    var doubledArea: Double { area * 2 }
}
struct Rectangle: AreaProviding {
    let width: Double
    let height: Double
    var area: Double { width * height }
}
final class FixedArea: AreaProviding {
    let area: Double
    init(area: Double) { self.area = area }
}
func totalArea<T: AreaProviding>(_ items: [T]) -> Double {
    items.reduce(0) { $0 + $1.area }
}
let rectangles = [Rectangle(width: 3, height: 4)]
assert(totalArea(rectangles) == 12)
assert(rectangles[0].doubledArea == 24)
let other: any AreaProviding = FixedArea(area: 5)
assert(other.area == 5)

The dimensions here are small, finite illustrative values; a public geometry API would define validation and numeric range requirements. The generic function accepts a homogeneous array of a conforming type; the existential value can hold different conforming implementations.

I would use a small protocol to express a capability or replaceable service, especially across unrelated types and test doubles. I would use inheritance where substitutability, identity or a framework's base class justifies it. Keep behavior that callers need to dispatch polymorphically in protocol requirements, rather than assuming every extension-only method behaves like an override. Neither approach guarantees faster execution or better architecture; excessive protocols and indirection can make a simple model harder to understand.

Swift protocols, Swift value and reference types

Related Questions