我正在使用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()
}
}
}
答案 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()
}
}
}