Swift - Extension to make a type conform to a protocol

Introduction

You can use extensions to make a type conform to a protocol.

For example, you can make the Int type conform to the Blinkable protocol described earlier:

Demo

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 Int  : Runnable { /*from  w  w  w.j  a v a 2 s. c om*/
    var isRuning  : Bool { 
        return false; 
    } 

    var runningSpeed  : Double { 
        get { 
            return 0.0; 
        } 
        set { 
            // Do nothing 
        } 
    } 

    func startRuning(runningSpeed  : Double) { 
        print("I am the integer \(self). Hi") 
    } 
} 
print(2.isRuning) // = false 
print(2.startRuning(runningSpeed: 2.0))

Result

Related Topic