Swift復習系列:控制流之Switch語句

Switch語句

Objective-C中的Switch語句不同,在Swift中,Switch語句在每個case結(jié)束之后不必通過break來跳出循環(huán),也不會貫穿到執(zhí)行下一步。

下面來說一下使用到時Switch語句的幾種情況,

1.單值匹配
        let testString = "t"
        switch testString
        {
        case "t":
            print("匹配成功!")
        case "T":
            print("匹配失敗!")
        default:
            print("匹配失敗!")
        }

運行結(jié)果:匹配成功!

2.多值匹配
        let testString = "t"
        switch testString
        {
        case "t","T":
            print("匹配成功!")
        default:
            print("匹配失敗!")
        }

運行結(jié)果:匹配成功!

3.區(qū)間匹配
        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)")

運行結(jié)果: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("驗證結(jié)果未知")
        }

運行結(jié)果:Login success

5.值綁定

SwiftSwitch語句中,case分支允許將匹配到的值綁定到一個臨時常量或變量上,并在分支體系內(nèi)使用,這種就是值綁定。如下,

        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))")
        }

運行結(jié)果:On the x-axis with an x value of 2

6.Where條件匹配

SwiftSwitch語句中,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))")
        }

運行結(jié)果:The point is (233,250)

7.符合匹配請參考上面的多值匹配
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容