I have a protocol that looks like this:
protocol MyProtocol {
associatedtype SpeedType
var name: String {get set}
func forward(_: SpeedType)
}
I made 2 simple classes that conform to this protocol:
class A: MyProtocol {
typealias SpeedType = Double
var name: String
init(name:String) {
self.name = name
}
func forward(_ s: Double) {
print("Moving \(s) km/h")
}
}
class B: MyProtocol {
typealias SpeedType = Int
var name: String
init(name:String) {
self.name = name
}
func forward(_ s: Int) {
print("Moving \(s) km/h")
}
}
What I want to achieve is to be able to declare a variable of type MyProtocol, and initialize it later like so:
let x: Bool = true
var person: MyProtocol
if x {
person = A(name: "Robot")
} else {
person = B(name: "Human")
}
Before I made forward() method "generic" I was able to do this, however now I am getting the next error: Protocol "MyProtocol" can only be used as generic constraint because it has Self or associated type requirement.
So my goal is to have a method forward() that can take as an argument parameter of a type that I specify, and also be able to declare a variable of a type that conforms to my protocol.