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
casein aswitchstatement is the same asiforelse ifinif-else if-elsechain.The
defaultblock in aswitchstatement is the same as theelseblock inif-elsestatements.
Last updated
Was this helpful?