Swift - Protocol Property Requirements

Introduction

Besides specifying methods to implement, a protocol can specify properties that a confirming class needs to implement.

As an example, consider the following Drivable :


protocol Drivable {
      var model: String {get set}
      var doors: Int {get set}
      var currentSpeed: Int {get}
}

The Drivable protocol specifies three properties that need to be implemented.

It does not specify whether you need to implement stored or computed properties.

It just specifies the name and type, as well as whether each property is settable or gettable.

It is up to the implementing class to decide how to implement the properties.

The following code shows the Truck class conforming to the Drivable :

protocol  Movable {
    func accelerate ()
    func decelerate ()
}
protocol Drivable {
      var model: String {get set}
      var doors: Int {get set}
      var currentSpeed: Int {get}
}

@objc class Truck: Movable, Drivable  {
    var speed = 0

    var model: String = ""
    var doors: Int = 0

    var currentSpeed: Int {
           return speed
    }

    func accelerate() {
          ...
    }
    ...
}

Here, both the model and doors properties are implemented as stored properties.

The currentSpeed property is implemented as a read-only computed property, as it is specified as only gettable in the protocol.

Related Topic