美文网首页
Swift复习系列:控制流之Switch语句

Swift复习系列:控制流之Switch语句

作者: ZYiDa | 来源:发表于2017-09-07 09:51 被阅读12次

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.值绑定

SwiftSwitch语句中,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条件匹配

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

运行结果:The point is (233,250)

7.符合匹配请参考上面的多值匹配

相关文章

网友评论

      本文标题:Swift复习系列:控制流之Switch语句

      本文链接:https://www.haomeiwen.com/subject/rsbbjxtx.html