Lantua
2
Usually when compiler fails to infer generic types, one of the constraint for generic is missing.
This case fails because R is not guaranteed to be MetalMickey in that function.
static func defineCommands<R>(_ builder: CommandBuilder<R>) where R: Robot & Programmable {
/// !!! Here's the problem
if let dance = dance as? CommandBinding<R, DanceCommand> {
builder.add(dance)
}
}
If you look closely R can be other Robots, say WoodMickey, but dance is fixed to MetalMickey.
Yes. the question is how to solve this? The function requirement in Programmable needs to then constrain on Self, but that then prevents use of Programmable in “as?” And then we cannot call the defineCommands function on programmable robots.
Lantua
4
On a side note, you don’t need to store command and robot in CommandBinding, R and C already contain all the information and you can just use them.
class CommandBinding<R, C> where R: Robot, C: Command {
func displayText() -> String {
return "\(C.name) on \(R.description)"
}
}
let dance = CommandBinding<MetalMickey, DanceCommand>()
1 Like
Lantua
5
Is there a scenario Programmable doesn’t imply Robot? How would defineCommands play out in those scenario?
If all the Programmable are Robot, you can likely do:
protocol Programmable: Robot {
static func defineCommands(_ builder: CommandBuilder<Self>)
}