对于来这里只是想知道如何在 Swift 中使用 switch 语句的人来说,这是一个更通用的答案。
一般用法
switch someValue {
case valueOne:
// executable code
case valueTwo:
// executable code
default:
// executable code
}
例子
let someValue = "horse"
switch someValue {
case "horse":
print("eats grass")
case "wolf":
print("eats meat")
default:
print("no match")
}
注意事项:
- 不需要
break 语句。这是默认行为。 Swift switch 案例不会“失败”。如果您希望他们在下一个案例中使用代码,您必须明确使用 fallthrough 关键字。
- 每个案例都必须包含可执行代码。如果您想忽略一个案例,您可以添加一个
break 语句。
- 案例必须详尽无遗。也就是说,它们必须涵盖所有可能的值。如果包含足够多的
case 语句不可行,则可以最后包含 default 语句以捕获任何其他值。
Swift switch 语句非常灵活。以下部分包括其他一些使用它的方法。
匹配多个值
如果您使用逗号分隔值,则可以在一个案例中匹配多个值。这称为复合案例。
let someValue = "e"
switch someValue {
case "a", "b", "c":
// executable code
case "d", "e":
// executable code
default:
// executable code
}
您还可以匹配整个间隔。
let someValue = 4
switch someValue {
case 0..<10:
// executable code
case 10...100:
// executable code
default:
// executable code
}
您甚至可以使用 元组。本示例改编自documentation。
let aPoint = (1, 1)
switch aPoint {
case (0, 0):
// only catches an exact match for first and second
case (_, 0):
// any first, exact second
case (-2...2, -2...2):
// range for first and second
default:
// catches anything else
}
值绑定
有时您可能希望从switch 值创建一个临时常量或变量。您可以在 case 语句之后立即执行此操作。在任何使用值绑定的地方,它将匹配任何值。这类似于在上面的元组示例中使用_。以下两个示例是从documentation 修改而来的。
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
// can use x here
case (0, let y):
// can use y here
case let (x, y):
// can use x or y here, matches anything so no "default" case is necessary
}
您可以使用 where 关键字进一步优化匹配。
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
// executable code
case let (x, y) where x == -y:
// executable code
case let (x, y):
// executable code
}
进一步研究