复制一段《The Swift Programming Language》上的代码
let vegetable = "red pepper"
switch vegetable{
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber","watercress":
let vegetableComment = "That would make a good tea sandwich."
//switch支持所有类型的数据,以及多种比较运算——没有限制为必须是整数,也没有限制为必须测试相等(tests for equality 真的是这样翻译的吗?)
case let x where x.hasSuffix("pepper"):
let vagetableComment = "Is it a spicy \(x)?"
//switch语句要求必须覆盖所有的可能,否则报错'switch must be exhaustive, consider adding a default cla'
default:
print("不能没有default")
}
不需要写break
执行完匹配到的case后,程序会跳出switch,而不是继续执行下一个case,所以不需要在case的代码后面添加break来跳出switch。