Swift - Protocol Initializer Requirements

Introduction

You can enforce a class to implement an initializer using a protocol.

By using Protocol you can enforce that a conforming class implements the initializer as follows:

protocol Drivable {
     init(model:String)

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

Here, for the Car class, if it now conforms to the Drivable , it needs to implement the initializer:


@objc class Car: Drivable  {
    var speed = 0
    var model: String = ""
    var doors: Int = 0

    required init(model:String) {
        self.model = model
    }

    var currentSpeed: Int {
        return speed
    }
...

You need the required keyword to ensure that subclasses of Car also provide an implementation for the initializer.

Related Topic