Swift - Switch Fallthrough statement

Introduction

Swift does not support fallthrough in the Switch statement.

If you are familiar with C/C++, you would be tempted to do the following:

var grade: Character
grade = "B"
switch grade {
    case "A":
    case "B":
    case "C":
    case "D":
        print("Passed")
    case "F":
        print("Failed")
    default:
        print("Undefined")
}

This is not allowed in Swift.

In Swift, each case must have at least one executable statement.

To implement the fallthrough behavior in Swift, you need to explicitly use the fallthrough keyword:

Demo

var grade: Character
grade = "A"//w  ww  .ja  v a 2 s  .  c  om

switch grade {
    case "A":
         fallthrough
    case "B":
         fallthrough
    case "C":
         fallthrough
    case "D":
         print("Passed")
    case "F":
         print("Failed")
    default:
         print("Undefined")
}

Result

Here, after matching the first case ("A"), the execution will fallthrough to the next case ("B"), which will then fallthrough to the next case ("C"), and finally the next case ("D").

The Switch statement ends after outputting the line "Passed."

To not only output a pass or fail message after checking the grade, but also output a more detailed message depending on the grade.

You could do the following:

Demo

var grade: Character
grade = "A"/*from   w  w  w.  j  a  v a  2  s. co m*/
switch grade {
    case "A":
         print ("Excellent! ")
         fallthrough
    case "B":
         print ("Well done! ")
        fallthrough
    case "C":
         print ("Good! ")
         fallthrough
    case "D":
         print ("You have passed.")
    case "F":
        print("Failed")
    default:
        print("Undefined")
}

Result

Related Topic