The Switch statement works with tuples, an ordered set of numbers.
Suppose you have the following tuples:
//(math, science) var scores = (70,40)
The scores tuple stores the score for the math and science examinations, respectively.
You can use the Switch statement to check the scores for each subject simultaneously.
Consider the following example:
//(math, science) var scores = (70,40) switch scores {//www .j ava 2s . co m 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!") }
Here, if the scores for both subjects are 0, the first case will match (0,0).
If both scores are 100, the second case will match (100,100).
The third case (50...100,_ ) will only match the score for the math subject-if it is between 50 and 100.
The underscore _ matches any value for the second subject (science).
The fourth case matches any value for the math subject and checks to see if the science subject is between 50 and 100.
If the score is (70, 40), the statement "Math pass!" will be output.
If the score is (40, 88), the statement "Science pass!" will be output.
If the score is (30, 20), the statement "Both failed" will be output.
In Swift, you are allowed to have overlapping cases.
You might have more than one match with the different cases.
The first matching case will always be executed.