Swift - Value Bindings in switch statement

Introduction

Consider the following code

//(math, science)
var scores =  (70,40)

switch scores {
   case  (0,0):
       print("This is not good!")
   case  (100,100):
       print("Perfect scores!")
   case  (50...100, _) :
       print("Math passed!")
   case  (_, 50...100):
       print("Science passed!")
   default:
       print("Both failed!")
}

The following two cases in which you try to match the score of one subject and ignore another:

case (50...100, _):    //ignore science
case (_, 50...100):    //ignore math

But what if after matching the score of one subject you want to get the score of the other?

In Swift, the Switch statement allows you to bind the value(s) its matches to temporary variables or constants.

This is known as value-binding.

The example used in the previous section can be modified to demonstrate value-binding:

Demo

//(math, science)
var scores =  (70,60)
switch scores {//from w w  w  . j  ava  2 s. co m
   case  (0,0):
       print("This is not good!")
   case (100,100):
       print("Perfect score!")
   case  (50...100, let science ):
        print("Math passed!")
        if science<50 {
            print("But Science failed!")
        } else {
            print("And Science passed too!")
        }
   case  (let math , 50...100):
        print("Science passed!")
        if math<50 {
            print("But Math failed!")
        } else {
            print("And Math passed too!")
        }
   default:
        print("Both failed!")
}

Result

Here, science and math are declared as constants using the let keyword.

However, you could also declare them as variables using the var keyword.

If they were declared as variables, all changes made would only have an effect within the body of the case.

In the third case statement, after matching the score for the math subject, you assign the score of the science subject to the science constant indicated using the let keyword:

case (50...100, let science ):
      print("Math passed!")
if science<50 {
      print("But Science failed!")
} else {
      print("And Science passed too!")
}

You can then use the science variable to determine its passing status.

Likewise, you do the same to the fourth case statement:

case  (let math , 50...100):
    print("Science passed!")
if math<50 {
    print("But Math failed!")
} else {
    print("And Math passed too!")
}

Related Topic