我有这两个类:
class State1 { static func getInfo() - >字符串{ 返回“sometext1” }}
class State2 { static func getInfo() - >字符串{ 返回“sometext2”……
如果类没有做太多,我只是将成员函数放在枚举中
enum State{ case state1 case state2 func getInfo() -> String { switch self { case .state1: return "sometext1" case .state2: return "sometext2" } } } var currentState = State.state1 print(currentState) print(currentState.getInfo())
如果你真的希望States拥有自己的类,你必须声明它们扩展相同的超类或实现相同的协议,并在枚举中使用该超类/协议。
protocol StateProtocol { static func getInfo() -> String } class State1 : StateProtocol { static func getInfo() -> String { return "sometext1" } } class State2 : StateProtocol { static func getInfo() -> String { return "sometext2" } } enum State { case state1 case state2 var instance: StateProtocol.Type { switch self { case .state1: return State1.self case .state2: return State2.self } } } var currentState = State.state1.instance print(currentState) //prints State1 print(currentState.getInfo())
虽然我不太愿意回来 Type 该类只是为了使用它的静态方法。
Type
使用State类作为实例而不仅仅使用它的静态方法更合乎逻辑。 (为什么在变量实例不是实例时将其命名?)
class StateClass { func getInfo() -> String { return "default text" } } class State1 : StateClass { override func getInfo() -> String { return "sometext1" } static let instance = State1() } class State2 : StateClass { override func getInfo() -> String { return "sometext2" } static let instance = State2() } enum State{ case state1 case state2 var instance : StateClass { switch self{ case .state1: return State1.instance case .state2: return State2.instance } } } var currentState = State.state1.instance print(currentState) print(currentState.getInfo())