Swift - Using break in switch statement

Introduction

The Break statement is useful in the Switch statement.

You cannot leave the case statement empty, like this:

Demo

var percentage = 85
switch percentage {
    case 0...20:/*from   w w w . ja v a  2  s  . c o  m*/
        print("Group 1")
    case 21...40:
        print("Group 2")
    case 41...60:
        print("Group 3")
    case 61...80:
        print("Group 4")
    case 81...100:
        print("Group 5")
     default:
         //each case must have an executable statement
         // comments like this do not count as executable statement
}

As each case in a Switch statement must have at least an executable statement, you can use a Break statement, like this:

Demo

var percentage = 85
switch percentage {
    case 0...20:/*from   ww  w.jav a 2 s  .c  o  m*/
        print("Group 1")
    case 21...40:
        print("Group 2")
    case 41...60:
        print("Group 3")
    case 61...80:
        print("Group 4")
    case 81...100:
        print("Group 5")
    default:
        break
}

Result

The preceding Break statement will end the execution of the Switch statement.

Related Topic