使用枚举快速存储当前状态类

时间:2019-03-13 05:45:50

标签: swift

我有这两节课:

class State1 {
    static func getInfo() -> String {
        return "sometext1"
    }
}

class State2 {
    static func getInfo() -> String {
        return "sometext2"
    }
}

我也有用于状态的枚举:

enum State {
    case state1
    case state2

    var instance: Any {
        switch self {
        case .state1:
            return State1.self
        case .state2:
            return State2.self
        }
    }
}

我正在尝试将当前状态存储在变量中,并基于枚举调用类的方法:

var currentState = State.state1.instance
print(currentState) //prints State1

currentState.getInfo() //currentState is of type Any so not possible to call State1 methods

有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

如果这些类做的不多,我将把成员函数放在枚举中

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())

如果您确实希望州拥有自己的类,则必须声明它们扩展相同的超类或实现相同的协议,并在枚举中使用该超类/协议。

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并不满意。

使用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())