2015-10-16 28 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

非常感謝! –