为什么 ~= 不适用于枚举和字符串?

Why doesn't ~= work on enums and strings?

当我试图回答另一个问题时,我发现这段代码不起作用:

enum Response {
    case positive
    case negative
    case neutral
}

func ~=(pattern: Response, value: String) -> Bool {
    switch pattern {
    case .positive:
        return ["yep", "yes", "yay", "definitely", "ok", "correct"]
            .contains(value.lowercased())
    case .negative:
        return ["no", "nope", "nah", "definitely not", "no way"]
            .contains(value.lowercased())
    case .neutral:
        return ["meh", "don't know", "indifferent", "don't care"]
            .contains(value.lowercased())
    }
}

switch "yep" {
case Response.positive:
    print("That was a positive response")
case Response.negative:
    print("That was a negative response")
case Response.neutral:
    print("That was a neutral response")
default:
    print("Something else")
}

我试图使用 ~= 运算符允许字符串与 Response 枚举之间进行模式匹配,这样我就可以将字符串分类为正面、负面或中性响应(对迅速的)。

是的,我可以将我接受的每种响应的字符串值直接写入开关案例,比如

case "yep", "yes", "yay", "definitely", "ok", "correct":
    print("That was a positive response")

但我认为说 case Response.positive 会创建另一层抽象,并允许后期绑定。例如,我可以从文件中读取可接受的响应。

据我所知,第一个代码片段应该有效。我定义了一个 ~= 运算符。我已经明确说明了 switch case 中的枚举值。文档没有说枚举不允许 ~= 。甚至 print(Response.positive ~= "yep") 打印 true但是 switch cases 发出错误:

Enum case 'positive' is not a member of type 'String'

(当然不是!你个笨蛋!:D)

为什么它不起作用,我该如何解决?

以下列符号工作。使用 Xcode 11.4

测试
switch "yep" {
case .positive:
    print("That was a positive response")
case .negative:
    print("That was a negative response")
case .neutral:
    print("That was a neutral response")
default:
    print("Something else")
}