Swift - Custom Type Protocols

Introduction

A protocol is the interface.

When you define a protocol, you're creating properties and methods that classes can declare that they have.

A protocol doesn't provide any actual implementation.

For example, to create a protocol that describes any object that can run on and off, you could use this:

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 
} 

Once you have a protocol, you can create classes that conform to that protocol.

One class can implement more than one protocols.

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 
} 

class Car  : Runnable { 
    var isRuning: Bool = false 

    var runningSpeed: Double = 0 

    func startRuning(runningSpeed: Double) { 
        print("I am a light and I am now running") 

        isRuning = true /*ww w  .j  a  va2 s  . c  o m*/

        self.runningSpeed = runningSpeed 
    } 
} 
class Plane  : Runnable { 
    var isRuning: Bool = false 

    var runningSpeed  : Double = 0.0 

    func startRuning(runningSpeed  : Double) { 
        print("I am a lighthouse, and I am now running") 
        isRuning = true 
        self.runningSpeed = runningSpeed 
    } 
} 

var aRuningThing  : Runnable 
// can be ANY object that has the Runnable protocol 

aRuningThing = Car() 

aRuningThing.startRuning(runningSpeed: 4.0) 
// prints "I am a light and I am now running" 
print(aRuningThing.runningSpeed) // = 4.0 

aRuningThing = Plane()

Result

Protocols can conform to other protocols.

protocol ControllableRun  : Runnable { 
    func stopRuning() 
} 

Related Topics