【问题标题】:Why is this Swift switch statement with two enums not exhaustive?为什么这个带有两个枚举的 Swift switch 语句并不详尽?
【发布时间】:2017-04-24 21:36:01
【问题描述】:

我正在编写一些 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")
        }
    }
}

打印出来的:

one, _
one, _
one, _
one, _
_, one
two, _
two, _
two, _
_, one
_, two
three, three
three, four
_, one
_, two
four, three
four, four

我希望它在没有默认子句的情况下编译,但编译器给出“错误:切换必须详尽,考虑添加默认子句”。如果我添加 default 子句,它会编译并运行良好,但当然它永远不会遇到 default 子句,因为所有前面的 case 语句都处理两个枚举的每个变体。

default 子句并没有真正损害任何东西,但我真的很想了解为什么编译器不认为此开关是详尽无遗的。有什么想法吗?

【问题讨论】:

  • 如果您从枚举和所有关联的值和案例中删除 .three.four,如果没有默认值,它仍然会抱怨。虽然如果你添加case (_, _):,你就不需要default,但在这种情况下基本上是一样的。
  • 仅供参考,我刚刚将此修复推送给大师。我希望在 Swift 4 中实现这个和模式最小化警告。

标签: swift enums switch-statement


【解决方案1】:

在 Twitter 上,CodaFi pointed me towards 如下,这表明这是当前版本的 Swift 编译器的错误/缺陷。

https://bugs.swift.org/browse/SR-483

https://bugs.swift.org/browse/SR-1313

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多