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中做到這一點?
有沒有辦法來約束RawRepresentable到一個地方RawValue是一個Int? –
@jackwilsdon:是:) –
非常感謝! –