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)