Switch语句
与
Objective-C
中的Switch
语句不同,在Swift
中,Switch
语句在每个case
结束之后不必通过break
来跳出循环,也不会贯穿到执行下一步。
下面来说一下使用到时Switch语句的几种情况,
1.单值匹配
let testString = "t"
switch testString
{
case "t":
print("匹配成功!")
case "T":
print("匹配失败!")
default:
print("匹配失败!")
}
运行结果:匹配成功!
2.多值匹配
let testString = "t"
switch testString
{
case "t","T":
print("匹配成功!")
default:
print("匹配失败!")
}
运行结果:匹配成功!
3.区间匹配
let testValue = 233
var valueString:String = ""
switch testValue
{
case 0...50:
valueString = "My test"
case 51...100:
valueString = "My Wifi"
case 101...200:
valueString = "You are 233"
default:
valueString = "Default Value"
}
print("\(valueString)")
运行结果:Default Value
4.元组匹配
let tupleValue = ("test",false)
switch tupleValue
{
case ("demo",false):
print("System Error")
case ("test",true):
print("404 not found")
case ("test",false):
print("Login success")
default:
print("验证结果未知")
}
运行结果:Login success
5.值绑定
在Swift
的Switch
语句中,case
分支允许将匹配到的值绑定到一个临时常量或变量上,并在分支体系内使用,这种就是值绑定
。如下,
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print("On the x-axis with an x value of \(x)")
case (0, let y):
print("On the y-axis with a y value of \(y)")
case let (x, y):
print("Somewhere else at (\(x), \(y))")
}
运行结果:On the x-axis with an x value of 2
6.Where
条件匹配
在Swift
的Switch
语句中,case
分支允许使用Where
来进行额外的条件判断。如下
let testValue = (233,250)
switch testValue {
case let(x,y) where x == y:
print("The point is (\(x),\(y))")
case let(x,y) where x < y:
print("The point is (\(x),\(y))")
default:
print("The point is (\(0),\(0))")
}
运行结果:The point is (233,250)
网友评论