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
The guard where CONDITION
binds only to .Y
.
case .X where false, .Y where false:
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With