To conform to a protocol, specify the protocol name(s) after the class name, as shown here:
class ClassName : ProtocolName1, ProtocolName2{
...
}
If you are conforming to more than one protocol, separate them using a comma ,
If your class is extending from another class, specify the protocol name(s) after the class it is extending:
class ClassName : BaseClass, ProtocolName1, ProtocolName2{
...
}
The following code shows an example of how to conform to a protocol:
protocol Movable { func accelerate () func decelerate () } class Truck: Movable { ... }
Here, the Truck class is said to "conform to the Movable."
Any class that conforms to the Movable must implement the methods declared in it.
To conform to the Movable protocol, the Truck class might look like this:
class Truck: Movable { var speed = 0 func accelerate() { speed += 10 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)") } }
In addition to implementing the accelerate() and decelerate() methods that are declared in Movable.
The Truck class can implement other methods as required.
If any of the methods declared in Movable are not implemented in the Truck class, the compiler will flag an error.
You can now create an instance of the Truck class and call its various methods to accelerate the truck, decelerate it, as well as make it come to a stop:
protocol Movable { func accelerate () func decelerate () } class Truck: Movable { var speed = 0 func accelerate() { speed += 10 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)") } } 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