Apple had added a new feature to the protocol i.e. protocol extension.While it may only seem like a minor feature at first, but this improved feature in swift allow us for a new type of programming i.e. protocol-oriented programming.

Protocols are not new to iOS developer but the idea that we can extend an existing type to adopt and conform to a new protocol, even if you do not have access to the source code for the existing type. Extensions can add new properties, methods, and subscripts to an existing type, and are therefore able to add any requirements that a protocol may demand.

Now let understand protocol-oriented programming by a simple example:

protocol Vehicle {
  var color:UIColor { get set }
  var topSpeed:Double { get set }
  var wheels:Int { get }
  var seats:Int { get }
}

This defines a simple protocol Vehicle with some properties.

Now let extend this protocol with two common feature i.e. starting and stopping a vehicle.

extension Vehicle {
  func start() {
    print("Started running...")
  }

  func stop() {
    print("Stopped.")
  }
}

Now, any type that conforms to the Vehicle protocol will automatically receive the start() and the stop() methods. You may have noticed that I provided a function definition rather than a function declaration.

Next, create a structure that conforms to Vehicle protocol.

struct Car:Vehicle {
  var color: UIColor = UIColor.redColor()
  var topSpeed: Double = 200.0
  var wheels: Int = 4
  var seats: Int = 4
}

Now suppose there is a class called Factory that simply creates Car and test it.

class Factory {
  var car:Car?
  func createCar() {
    car = Car(color:UIColor.redColor(), topSpeed:220, wheels:4, seats:4)
  }

  func testCar() {
    car?.start()
    car?.stop()
  }
}

What make protocol-oriented programming different from object-oriented programming.

  • Protocol-oriented programming should start with a protocol rather than a superclass.
  • We can use protocol extensions to add functionality to the types that conform to that protocol rather than subclassing and adding functionality.
  • Use of value types(struct,enum,etc.) rather than reference types(class).

References