swift - 切换映射 : how to map enum to value without switch

标签 swift enums switch-statement

假设我想将枚举转换为另一个值:

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/

相关文章:

ios - 向 uipageviewcontroller 添加分页

java - 为什么 Java 枚举不能是最终的?

c# - 关于Enum操作

c# - Nullable Long switch 语句在 VS2015 中没有产生预期的输出

swift - 在 Swift 中调试打印自定义类的“正确”方法

variables - Swift 访问闭包内的类变量

ios - 向玩家添加观察者时出错

c# - 获取包含枚举值的整数表示的字符串

c - 多个 If-Else 语句 VS。 C 语言 While 循环中的 Switch 语句

regex - 如果字符串包含子字符串,为什么我的条件不满足?