📅  最后修改于: 2021-01-11 07:31:09             🧑  作者: Mango
Switch语句在匹配复杂模式时用作长if-else-if语句的替代。它提供了多种情况,可以根据不同的条件执行不同的操作。
switch variable/expression {
case value1:
// statements
case value2:
// statements
default:
// statements
}
let dayOfWeek = 6
switch dayOfWeek {
case 1:
print("It is Sunday today")
case 2:
print("It is Monday today")
case 3:
print("It is Tuesday today")
case 4:
print("It is Wednesday today")
case 5:
print("It is Thursday today")
case 6:
print("It is Friday today")
case 7:
print("It is Saturday today")
default:
print("Invalid day")
}
输出:
It is Friday today
在上面的程序中,switch语句首先将dayOfWeek值与案例1匹配。由于dayOfWeek值与第一个案例值1不匹配,因此它会下降到下一个案例,直到找到匹配项。在情况6中找到匹配项,打印声明,然后switch语句终止。
如果要继续控制到下一种情况,则在switch语句中使用fallthrough语句。
let dayOfWeek = 5
switch dayOfWeek {
case 1 :
print("It is Sunday today")
case 2:
print("It is Monday today")
case 3:
print("It is Tuesday today")
case 4:
print("It is Wednesday today")
case 5:
print("It is Thursday today")
fallthrough
case 6:
print("It is Friday today")
case 7:
print("It is Saturday today")
default:
print("Invalid day")
}
输出:
It is Thursday today
It is Friday today
在上面的示例中,您可以看到案例5执行了语句print(“今天是星期三”),而fallthrough关键字进入到case6,它打印了print(“今天是星期四”)。