The switch statement ignores the Where clause for several cases

Consider the following scenario:

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
}

Even if the sentence whereis equal false, this fragment will print x or y.

No mention of this. Does anyone have an idea how to reorganize this without duplicating code in the first case?

I used fallthough, but the sentence is wherenow duplicated

+4
source share
3 answers

The protector is where CONDITIONattached only to .Y.

case .X where false, .Y where false:
+5
source

This is because it matches .Xcase

Basically your switch will be the same:

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

To have them in the same thing case, you probably have to do something like this:

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
}
+3

case:

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

"guard-clause" "".

, :

let condition:Bool = ...

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

, .

+1
source

All Articles