基本用法
let number = 3
switch number {
case 1:
print("One!")
case 2:
print("Two!")
case 3:
print("Three!")
default:
print("Not One, Two or Three")
}
switch 语句也适用于整数以外的数据类型。它们适用于任何数据类型。这是一个打开字符串的示例:
let string = "Dog"
switch string {
case "Cat", "Dog":
print("Animal is a house pet.")
default:
print("Animal is not a house pet.")
}
这将打印以下内容:
Animal is a house pet.