Swift Generics: no initializers available

Why does the code below compile with the error: "T" cannot be built because it has no initializers available

let drive = Drive<Car>()

class Car : Steering {
    init() { }
    func turnWheel() { }
}

protocol Steering {
    func turnWheel()
}

class Drive<T:Steering> {    
    func Go() {
        var vehicle = T()
        vehicle.turnWheel()
    }
}

      

+3


source to share


2 answers


Because it is T

limited Steering

. Your constraint says, "T can be any type that conforms to the protocol Steering

. However, if I have this class:

class Airplane : Steering {
    init(altitude : Int) {
    }

    func turnWheel() {
    }
}

      

All of a sudden, I have a type that matches Steering

and T

, but does not have an init that takes null parameters.



The solution is to add init to your protocol, ensuring that anything that matches it has the correct init.

protocol Steering {
    func turnWheel()
    init()
}

      

+6


source


You, as the compiler says, must provide an initializer with no parameters in the declaration Steering

.

Since T is only required to implement the steering protocol and you want to build it with T()

, the protocol Steering

requires a parameterless initializer to be guaranteed to be constructive.



protocol Steering {
    init();
    func turnWheel()
}

class Car : Steering {
    required init() { }
    func turnWheel() { }
}

      

+4


source







All Articles