Swift - Using extensions to define default implementations of your protocols


A default implementation lets you write a sensible implementation of parts of the protocol that will be used when classes conforming to the protocol don't provide them:

protocol Runnable { 
    // This property must be at least gettable 
    var isRuning  : Bool { get } 

    // This property must be gettable and settable 
    var runningSpeed: Double { get set } 

    // This function must exist, but what it does is up to the implementor 
    func startRuning(runningSpeed: Double) -> Void 
extension Runnable 
    func startRuning(runningSpeed: Double) { 
        print("I am running") 

With this default implementation of Runnable, if we now create a new class and don't provide the method call, it will still work:

class AnotherBlinker  : Blinkable { 
    var isBlinking: Bool = true 

    var blinkSpeed: Double = 0.0 
let anotherBlinker = AnotherBlinker() 
anotherBlinker.startBlinking(blinkSpeed: 3)

Related Topic