Tuesday, August 28, 2018

Protocol Extensions for Default and Convenient API


In this tutorial, let’s see how protocol extensions can be used as default and convenient API.

I am taking a Movable protocol which is having a move method.


     
  protocol Movable {
    func move(at minimumSpeed: Float)
  }


I am creating a class called Car which confirms to Movable protocol.


     
  class Car: Movable {
    
   }


This gives a build error.



We need to implement move method as Car is confirming to Movable.

Instead of this forced implementation, using protocol extensions, we can write default implementation.


     
  extension Movable {

    func move(at minimumSpeed: Float) {
      print("Moving @ \(minimumSpeed) MPH")
    }

  }

  let car = Car()
  car.move(at: 40.0)


This is how we can leverage protocol extensions for default implementations.

Now, What If I don’t want to mention the speed every time. I need to go with minimum speed 40.0 as default speed.

This can also be done using the protocol extensions, by having default value for minimumSpeed.


     
  extension Movable {

 func move(at minimumSpeed: Float = 40.0) 
  {
     print("Moving @ \(minimumSpeed) MPH")
  }

 }

 let car = Car()
 car.move()


Simple and useful. Isn’t it?

Hope this post is useful. Feel free to comment incase of any queries.


No comments:

Post a Comment