2015-10-16 69 views
0

我正在寻找一种方法来从使用它的类型的整数中获取枚举值。从它的类型创建枚举的实例

下面是我想要做的一个例子;

enum TestEnum: Int { 
    case A = 0 
    case B = 1 
    case C = 2 
} 

func createEnum<T>(value: Int, type: T.Type) -> T? { 
    // Some magic here 
} 

let a = createEnum(0, type: TestEnum.self) // Optional(TestEnum.A) 
let b = createEnum(1, type: TestEnum.self) // Optional(TestEnum.B) 
let c = createEnum(2, type: TestEnum.self) // Optional(TestEnum.C) 
let invalid = createEnum(3, type: TestEnum.self) // nil 

我知道你能得到的价值,像这样:

let a = TestEnum(rawValue: 0) // Optional(TestEnum.A) 
let b = TestEnum(rawValue: 1) // Optional(TestEnum.B) 
let c = TestEnum(rawValue: 2) // Optional(TestEnum.C) 
let invalid = TestEnum(rawValue: 4) // nil 

但是我希望能够“存储”枚举类型创建(在这种情况下,TestEnum)和然后再从一个值中创建它,如我的示例所示。

有没有办法在Swift中做到这一点?

回答

2

枚举具有基础类型符合具有RawValue担任副类型RawRepresentable 协议:

func createEnum<T : RawRepresentable >(value: T.RawValue, type: T.Type) -> T? { 
    return T(rawValue: value) 
} 

这样做是可以为您enum TestEnum: Int { ... }例如,而不是 限于Int为基础类型。

enum StrEnum : String { 
    case X = "x" 
    case Y = "y" 
} 

let x = createEnum("x", type: StrEnum.self) // Optional(StrEnum.X) 

如果要限制与底层类型Int功能来枚举再加入对通用占位另一个约束:

func createEnum<T : RawRepresentable where T.RawValue == Int>(value: Int, type: T.Type) -> T? { 
    return T(rawValue: value) 
} 
+0

有没有办法来约束RawRepresentable到一个地方RawValue是一个Int? –

+0

@jackwilsdon:是:) –

+1

非常感谢! –