Swift - Where Clause in switch statement

Introduction

You can use the Switch statement together with a where clause to check for additional conditions.

For example, to check if the scores for both subjects are greater than 80, you could write the following case:

Demo

//(math, science)
var scores =  (90,90)
    switch scores {
    case  (0,0):/* ww  w.  j a  va  2 s.  c  o m*/
        print("This is not good!")
    case (100,100):
        print("Perfect score!")
    case let  (math, science) where math > 80 && science > 80 :
         print ("Well done!")
    case (50...100, let science):
        print("Math pass!")
        if science<50 {
            print("But Science fail!")
        } else {
            print("And Science also pass!")
        }
    case (let math, 50...100):
        print("Science pass!")
        if math<50 {
            print("But Math fail!")
        } else {
            print("And Math also pass!")
        }
    case let (math, science):
        print("Math is \(math) and Science is \(science)")
}

Result

Here, the third case assigns the scores of the math and science subjects to the temporary variables math and science, respectively.

It uses the where clause to specify the condition that the scores for both math and science must be greater than 80.

To match the case where the math score is greater than the science score, specify the following where clause:

case let (math, science)  w here math > science :
print("You have done well for Math!")

Related Topic