我正在构建一个简单的状态引擎,我想要一个可以在其中移动的状态集合。
我想解决这个问题的方法是枚举可能的状态,这些状态也定义了表示该状态的相应类,这样如果我决定移动到那个状态,我就可以动态地构造状态。
在下面的代码中,我尝试构建一个运行良好的 State 对象的枚举。我卡住的地方是,我怎样才能访问这个枚举的值作为我可以从中调用静态构造函数方法的类型?在下面的代码中,我得到的错误是尝试使用枚举值调用 moveToState 并不代表 StartupStates 类型,它似乎...
所以问题真的是,为什么这不起作用,或者我有什么其他方式可以枚举类类型和/或类级别(静态)方法来调用构造函数?
public enum StartupStates<State> {
case Start(StartState)
case DownloadFiles(DownloadFilesState)
}
public protocol State {
var stateEngine : StateEngine {get set}
}
public class StateEngine
{
var currentState : State?
public func moveToState(newState : StartupStates<State>)
{
}
}
public class StartState : BaseState
{
func doStateTasks()
{
// Move to next state, downloading files
// ERROR IS HERE:
// "Cannot convert file of type '(DownloadFileState)->StartupStates<...>' to expected argument type 'StartupStates<State>'"
stateEngine.moveToState(StartupStates.DownloadFiles)
}
}
public class DownloadFilesState : BaseState
{
}
public class BaseState : State {
public var stateEngine : StateEngine
required public init( stateEngine : StateEngine ) {
self.stateEngine = stateEngine
}
public static func stateCreator(stateEngine : StateEngine) -> Self {
return self.init( stateEngine: stateEngine )
}
}