假设我想将枚举转换为另一个值:
enum MyEnum {
case a
case b
case c
}
let myEnum: MyEnum = .a
let string: String
switch myEnum {
case .a:
string = "a-string"
case .b:
string = "b-string"
case .c
string = "c-string"
}
在这个例子中,我将 MyEnum
转换为 String
(但也可以是其他类型)。
现在,它迫使我使用那个丑陋的switch
并为每个case
重复赋值操作string =
。
我真正想要的是这样的:
let string = switchMap(myEnum, [
(.a, "a-string"),
(.b, "b-string"),
(.c, "c-string")
])
他们我想实现它是这样的:
func switchMap<V, R>(_ value: V, _ patterns: [(V, R)]) -> R? {
for (k, v) in patterns {
switch value {
case k:
return v
default: ()
}
}
return nil
}
但是这给了我错误Expression pattern of type 'V' cannot match values of type 'V'
。
知道如何解决这个问题吗?也许以更好的方式? (理想情况下,我正在寻找类似于 Haskell 模式匹配的东西,就 os 语法而言)。
我也在寻找替代 swift
语句的东西,所以我希望我的输入接受 switch
会接受的任何模式。
Obs.:我知道,这个解决方案也不完美,因为它返回 R?
而不是 R
,但我认为我不能做得更好不仅如此,因为 switch
依赖于编译器知道它是详尽无遗的。
最佳答案
您可以将 rawValues 分配给案例:
enum MyEnum : String {
case a = "a"
case b = "b"
case c = "c"
}
然后只需使用 a.rawValue 等访问字符串值
关于swift - 切换映射 : how to map enum to value without switch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46347929/