下面的例子是判断(x,y)是否在矩形中,元组类型是(Int,Int)
复制代码let somePoint = (1, 1)
switch somePoint {
case (0, 0):
println("(0, 0) is at the origin")
case (_, 0):
println("((somePoint.0), 0) is on the x-axis")
case (0, _):
println("(0, (somePoint.1)) is on the y-axis")
case (-2...2, -2...2):
println("((somePoint.0), (somePoint.1)) is inside the box")
default:
println("((somePoint.0), (somePoint.1)) is outside of the box")
}
// prints "(1, 1) is inside the box"
和C语言不同,Swift可以判断元组是否符合条件。
数值绑定
在case匹配的同时,可以将switch语句中的值绑定给一个特定的常量或者变量,以便在case的语句中使用。比如:
复制代码
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
println("on the x-axis with an x value of (x)")
case (0, let y):
println("on the y-axis with a y value of (y)")
case let (x, y):
println("somewhere else at ((x), (y))")
}
// prints "on the x-axis with an x value of 2"
switch语句判断一个点是在x轴上还是y轴上,或者在其他地方。这里用到了匹配和数值绑定。第一种情况,如果点是(x,0)模式的,将值绑定到x上,这样在case语句中可以输出该值。同理如果在y轴上,就输出y的值。
Where关键词
switch语句可以使用where关键词来增加判断的条件,在下面的例子中:










