Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement ignores Where clause for multiple 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 though the where clause is false, this snippet will print x or y.

Haven't found any mention of it. Anyone has an idea how to refactor this without duplicating the code in the first case?

I used fallthough for now but the where clause is now duplicated

like image 488
Yariv Nissim Avatar asked Jan 08 '23 07:01

Yariv Nissim


2 Answers

The guard where CONDITION binds only to .Y.

case .X where false, .Y where false:
like image 175
Joop Eggen Avatar answered Jan 10 '23 20:01

Joop Eggen


That's because it matches .X case

Basicaly your switch is the same like this:

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
}

To have them in the same case, you'll 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
}
like image 33
Marius Fanu Avatar answered Jan 10 '23 20:01

Marius Fanu