4.3. Switch statements

Instead of if-else if-else chain, we can use switch statements if multiple statements are true. For example, the following code prints the name of the day of the week, depending on the value of the constant day. If the value of day is 1 through 7, the code prints the name of the day; else, it prints "Invalid!"

//switch statements...
let day = 5
switch day {
case 1:
    print("Sunday")
case 2:
    print("Monday")
case 3:
    print("Tuesday")
case 4:
    print("Wednesday")
case 5:
    print("Thursday")
case 6:
    print("Friday")
case 7:
    print("Saturday")
default:
    print("Invalid day")
}

Please note:

  • Each case in a switch statement is the same as if or else if in if-else if-else chain.

  • The default block in a switch statement is the same as the else block in if-else statements.

Last updated

Was this helpful?