将类型与Swift枚举大小写相关联吗?

Associating a type with a Swift enum case?

我正在使用Swift 2,我想将struct类型与enum中的每种情况相关联。

目前,我已通过向枚举type添加一个函数来解决此问题,该函数使用switch语句针对每种情况返回相关类型的实例,但我想知道这是否有必要。我知道您可以将字符串,整数等与Swift枚举关联,但是也可以关联类型吗?如果有帮助,该类型的所有结构都遵循相同的协议。

这是我现在正在做的,但是我想取消使用此功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public enum Thingy {

    case FirstThingy
    case SecondThingy

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

}


我想您是说您希望原始值的类型为ThingyType,但这是不可能的。

您可以做的是将type设为计算属性,以删除(),而只需使用thingy.type进行访问。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public enum Thingy {

    case FirstThingy
    case SecondThingy

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

}