1. Introduction
Protocol-Oriented Programming (POP) is a programming paradigm introduced by Swift which emphasizes the use of protocols and protocol extensions over traditional inheritance-based approaches. Swift’s POP allows developers to create flexible and reusable code, and is especially useful when multiple types share similar behaviors. Let’s delve into a practical example to understand this concept.
2. Source Code Example
// 1. Defining a protocol
protocol Drivable {
var isEngineRunning: Bool { get set }
func startEngine()
func stopEngine()
}
// 2. Protocol extension
extension Drivable {
mutating func startEngine() {
isEngineRunning = true
print("Engine started.")
}
mutating func stopEngine() {
isEngineRunning = false
print("Engine stopped.")
}
}
// 3. Struct conforming to Drivable
struct Car: Drivable {
var isEngineRunning = false
}
// 4. Using the Drivable protocol
var myCar = Car()
myCar.startEngine()
myCar.stopEngine()
Output:
Engine started. Engine stopped.
3. Step By Step Explanation
1. Defining a Protocol:
- We begin by defining a Drivable protocol that any type can adopt to become drivable. This protocol declares two methods: startEngine() and stopEngine(). Additionally, there’s a property requirement isEngineRunning to track the engine status.
2. Protocol Extension:
- Rather than leaving it to individual types to implement the methods, we provide default implementations within a protocol extension. This way, any type adopting Drivable gets these implementations for free, but can still override them if needed.
3. Struct Conforming to Drivable:
- Here, we have a Car struct that adopts the Drivable protocol. Since we have provided default implementations in the protocol extension, the Car struct doesn’t need to implement the methods itself.
- The Car struct only needs to provide its own storage for the isEngineRunning property as required by the Drivable protocol.
4. Using the Drivable Protocol:
- We create an instance of Car named myCar and use the methods startEngine() and stopEngine(). Even though we didn’t define these methods in Car, the struct inherits them from the protocol extension.
Swift's Protocol-Oriented Programming brings in the benefits of flexibility and reusability, allowing developers to write cleaner code by focusing on behaviors and contracts (protocols) rather than a rigid inheritance chain.
Comments
Post a Comment