由于Swift模式匹配中的顺序导致意外结果

时间:2021-04-07 22:35:35

Sorry for the "Shouldn't this work?" question. But I can't figure out a better way to phrase this.

对不起,“这不应该工作吗?”题。但我无法想出一个更好的方式来表达这一点。

enum MyEnum {
    case A, B, C
}

let tuple = (MyEnum.C, MyEnum.A)    
var x: String

switch tuple {
case (.A, _):
    x = "(A, something)"
case (_, .A):
    x = "(something, A)"
case (_, .B):
    x = "(something, B)"
case (.C, .C):
    x = "(C, C)"
default:
    x = "default"
}

x // -> "default"

x evaluates to "default", which means the default branch was taken.

x计算为“default”,表示采用了默认分支。

However, I was expecting "(something, A)" and the second case statement to match. From what I understood (_, .A) should match anything in the first tuple element, and .A in the second.

但是,我期待“(某事,A)”和第二个案例陈述相匹配。根据我的理解(_,。A)应该匹配第一个元组元素中的任何内容,而第二个元素中的.A匹配。

If I move the (_, .A) case to the top, it is matched as I expect it. Other tuples also match where I expect them to.

如果我将(_,.A)案例移到顶部,它会按照我的预期进行匹配。其他元组也匹配我期望的位置。

What am I missing? Why isn't this matched by the second case?

我错过了什么?为什么这不符合第二种情况?

1 个解决方案

#1


1  

This behavior has been corrected in beta 3. It now shows (Something, A) whatever the order is.

此行为已在beta 3中得到纠正。它现在显示(Something,A)无论顺序如何。

#1


1  

This behavior has been corrected in beta 3. It now shows (Something, A) whatever the order is.

此行为已在beta 3中得到纠正。它现在显示(Something,A)无论顺序如何。