In Swift, there is a strong emphasis on Protocol Oriented Programming (POP). The main idea of POP is to design architecture starting from protocols (interfaces) rather than base classes. Protocols provide flexibility in inheriting behavior through multiple chains, reducing code coupling.
Swift allows protocols to have default implementations (through extensions), facilitating code reuse without the need for class hierarchies. Classic OOP relies on inheritance between classes, which is limited to a single inheritance chain. POP is free from these constraints, allowing for composition and extensibility.
Code example:
protocol Drivable { func drive() } extension Drivable { func drive() { print("Driving forward!") } } struct Car: Drivable {} let car = Car() car.drive() // Outputs: Driving forward!
Can you add a stored property to a protocol extension?
Answer: No, you cannot add stored properties in protocol extensions, only computed properties and methods. For example,
// Error! extension Drivable { var speed: Int = 0 // Compilation error: Extensions may not contain stored properties }
Story
In a large project, developers tried to add stored properties through protocol extensions for state tracking. The code compiled with an error, requiring urgent architectural redesign in the middle of a sprint to use third-party solutions with objc_get/setAssociatedObject — which worsened code readability.
Story
A base class was implemented for different types of entities, and multiple inheritance was used through protocols. A developer confused the behavior of the default implementation in the extension and tried to override this method in a struct, expecting the struct's implementation to be called. As a result, it was hard to track the method call order.
Story
When scaling a module, protocols were used to separate responsibilities, but due to a lack of experience with POP, developers did not ensure clear dependencies between protocols. This led to code duplication and interface conflicts when merging several extensions in large development teams.