假设我想将枚举转换为另一个值:
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
并为每个string =
重复分配操作case
。
我真正想要的是这样的:
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
,但我不认为我能做得更好,因为{{1依赖编译器知道它是详尽无遗的。
答案 0 :(得分:1)
您可以将rawValues分配给案例:
enum MyEnum : String {
case a = "a"
case b = "b"
case c = "c"
}
然后只需使用a.rawValue等访问字符串值。