Switch 语句忽略多个案例的 Where 子句

Switch statement ignores Where clause for multiple cases

考虑以下场景:

enum XYZ {
  case X
  case Y
  case Z
}

let x = XYZ.X

switch x {
case .X, .Y where false:
  println("x or y")
case .Z:
  println("z")
default:
  println("default")
  break
}

即使 where 子句是 false,此代码段也会打印 x or y.

没有找到任何提及它的地方。任何人都知道如何在不复制第一种情况下的代码的情况下重构它?

我现在使用 fallthough,但 where 子句现在重复了

那是因为它符合 .X 大小写

基本上你的开关是这样的:

switch x {
case .X:
    println("x or y") // This is true, and that's why it prints 
case  .Y where false:
    println("x or y") // This never gets executed
case .Z:
    println("z")
default:
    println("default")
    break
}

要将它们放在同一个 case 中,您可能必须执行以下操作:

let x = XYZ.X

var condition = false
if x == .X || x == .Y {
    condition = true
}

switch x {
case _ where condition:
    println("x or y")
case .Z:
    println("z")
default:
    println("default")
    break
}

The grammer of a case label 是:

case-labelcase ­case-item-list ­:­
case-item-listpattern­ guard-clause­opt­ | pattern­ guard-clause­opt ­, ­case-item-list­

我们必须为每个 "pattern"s 写 "guard-clause"s。

如果你愿意,你可以:

let condition:Bool = ...

switch x {
case let x where (x == .X || x == .Y) && condition:
    // ...

但我觉得这样不好

守卫 where CONDITION 仅绑定到 .Y

case .X where false, .Y where false: