when I execute this code just the print("it is greater than zero")
gets executed but I have two cases where it's true, I've tried to use the fallthrough
keyword but it executes the next case block even if it's false, no matter what,
which in turn raises another question, when should I use fallthrough
keyword? if I want to forcefully execute the next block why don't just insert the code into the same block where fallthrough
sits?
Is there any way that the example below could print all cases that evaluate to true and still rule out all cases that evaluate to false?
let number = 1
switch number {
case _ where number > 0:
print("it is greater than zero")
case _ where number < 2:
print("it is less than two")
case _ where number < 0:
print("it is less than zero")
default:
print("default")
}
Thank you in advance for your answers!
The
switch
statement isn't for this purpose, and doesn't work this way. It's intent to to find a single true case. If you want to check multiple cases, that's just anif
statement:There is no equivalent
switch
for this. They're different control statements.As you've discovered,
fallthrough
exists to allow two cases to run the same block. That's what it's for; it doesn't check the other cases. As a rule, if you're usingcase _
extensively, you're probably not usingswitch
correctly in Swift and should be usingif
.