Swift - Protocol Optional Methods

Introduction

You have the option for the implementing class to determine whether it will implement a particular method.

You can do so by specifying a method within a protocol as an optional method using the optional keyword.

The following code snippet shows the Movable now has an optional method called accelerateBy() :


@objc  protocol Movable {
    func accelerate ()
    func decelerate ()
    optional func accelerateBy(amount:Int)
}

The @objc tag indicates to the compiler that your class is working with Objective-C.

You need to prefix the protocol with this tag in order to declare optional methods in your protocol, even if you do not intend to use your class with Objective-C code.

All optional methods are prefixed with the optional keyword.

Protocols prefixed with the @objc tag can only be applied to classes, not structures and enumerations.

In the Truck class, you can now choose to implement the optional accelerateBy() method if desired:

Demo

@objc  protocol Movable {
    func accelerate ()
    func decelerate ()
    optional func accelerateBy(amount:Int)
}

class Truck: Movable  {
    var speed = 0

    func accelerate() {
        speed += 10/*from   w  ww .j  a va2  s  . c  om*/
        if speed > 50 {
            speed = 50
        }
        printSpeed()
    }

    func decelerate()  {
        speed -= 10
        if speed<=0 {
            speed = 0
        }
        printSpeed()
    }

    func stop() {
        while speed>0 {
            decelerate ()
        }
    }

    func printSpeed() {
        print("Speed: \(speed)")
    }

    func accelerateBy(amount:Int) {
        speed += amount
        if speed > 50 {
            speed = 50
        }
        printSpeed()
     }
}


var c1 = Truck ()
c1.accelerate()    //Speed: 10
c1.accelerate()    //Speed: 20
c1.accelerate()    //Speed: 30
c1.accelerate()    //Speed: 40
c1.accelerate()    //Speed: 50
c1.decelerate()    //Speed: 40
c1.stop()          //Speed: 30

c1.accelerateBy(5) //Speed: 5
c1.accelerateBy(5) //Speed: 10

Related Topic