I'm writing a bit of Swift code (Swift 3.1, Xcode 8.3.2) that switches on two enums. I believe I've written an exhaustive list of cases, but the compiler disagrees with me. My code is a bit complicated, with some associated values and such, so I boiled this down to as simple an example as I could in a playground, like so:
我正在编写一些Swift代码(Swift 3.1,Xcode 8.3.2),它可以打开两个枚举。我相信我已经写了一个详尽的案例列表,但编译器不同意我的观点。我的代码有点复杂,有一些相关的值等,所以我把它简化为一个简单的例子,就像我在操场上一样,如下:
enum Test {
case one
case two
case three
case four
}
let allValues: [Test] = [.one, .two, .three, .four]
let test1 = Test.one
let test2 = Test.two
for i in 0..<4 {
for j in 0..<4 {
let test1 = allValues[i]
let test2 = allValues[j]
switch (test1, test2) {
case (.one, _):
print("one, _")
case (_, .one):
print("_, one")
case (.two, _):
print("two, _")
case (_, .two):
print("_, two")
case (.three, .three):
print("three, three")
case (.three, .four):
print("three, four")
case (.four, .three):
print("four, three")
case (.four, .four):
print("four, four")
//Won't compile with this commented out, but when enabled,
//we never print out "default"
// default:
// print("default")
}
}
}
Which prints out:
打印出来:
one, _
one, _
one, _
one, _
_, one
two, _
two, _
two, _
_, one
_, two
three, three
three, four
_, one
_, two
four, three
four, four
I would expect this to compile without the default clause, but the compiler gives "error: switch must be exhaustive, consider adding a default clause". If I add the default clause, it compiles and runs fine, but of course it never hits the default clause because all the previous case statements handle every variation of the two enums.
我希望这可以在没有default子句的情况下编译,但是编译器会给出“错误:switch必须是详尽的,考虑添加一个default子句”。如果我添加默认子句,它编译并运行正常,但当然它永远不会遇到默认子句,因为所有先前的case语句都处理两个枚举的每个变体。
The default clause doesn't really harm anything, but I'd really like to understand why this switch isn't considered exhaustive by the compiler. Any ideas?
默认子句并没有真正伤害任何东西,但我真的很想理解为什么编译器不认为这个开关是详尽无遗的。有任何想法吗?
1 个解决方案
#1
5
On Twitter, CodaFi pointed me towards the following, which indicates that it's a bug/shortcoming in the current version of the Swift compiler.
在Twitter上,CodaFi向我指出了以下内容,这表明它是当前版本的Swift编译器中的一个错误/缺点。
#1
5
On Twitter, CodaFi pointed me towards the following, which indicates that it's a bug/shortcoming in the current version of the Swift compiler.
在Twitter上,CodaFi向我指出了以下内容,这表明它是当前版本的Swift编译器中的一个错误/缺点。