将类型与Swift枚举案件相关联?

时间:2016-07-24 18:46:53

标签: swift enums

我正在使用Swift 2,我想将struct类型与enum中的每个案例相关联。

目前,我已经通过在enum中添加一个名为type的函数来解决这个问题,该函数使用switch语句为每个案例返回相关类型的实例,但我想知道这是否有必要。我知道你可以将字符串,整数等与Swift枚举关联起来,但也可以关联一个类型吗?如果有帮助的话,那种类型的所有结构都符合相同的协议。

这就是我现在正在做的事情,但我很乐意废除这个功能:

public enum Thingy {

    case FirstThingy
    case SecondThingy

    func type() -> ThingyType {
        switch self {
        case .FirstThingy:
            return FirstType()
        case .SecondThingy:
            return SecondType()
        }
    }

}

1 个答案:

答案 0 :(得分:1)

我认为你说你希望原始值属于ThingyType类型,但这是不可能的。

您可以做的是使type成为计算属性,删除(),只需要使用thingy.type访问它。

public enum Thingy {

    case FirstThingy
    case SecondThingy

    var type: ThingyType {
        switch self {
        case .FirstThingy:
            return FirstType()
        case .SecondThingy:
            return SecondType()
        }
    }

}