Swift中switch和switch在enum中和非enum中的区别

来源:互联网 发布:能力风暴机器人编程 编辑:程序博客网 时间:2024/04/29 03:29

对于swift中的switch感觉到非常棒,它会比我之前用过的语言中的switch应用要广得多,而且对于处理多值匹配简直强到爆,对于坐标的比较简直是绝配。

在Swift中的switch语法比c,java等语言感觉简便了很多,而且也能更加符合逻辑和对事物的严谨。

如下:

switch X1 {

case 1:

    // 省略

case 2,3:

    // 省略

default:

    // 省略

}

首先在X1的部分,可以使用变量,常量或者字面值。

然后在case表达式之后的语句省略了通常需要的break,return等控制流关键字,感觉这是太人性化了,

为了让条件控制可以在一个范围中,swift的switch也支持了 case xxx, xxx:这样的语法,这让我们也能够处理

条件在一定范围中的情况,就像sql语句中的in,很重要的是default是必须要添加的,这样让我们写程序的时候

能够自动增加严谨性,

关于default的使用,在enum中有所不同,当我们在enum中使用switch语句时,可以不使用default关键字,前提

条件是已经包含了enum中所有对象,如下:

enum Rank {

   case one, two, three

   func test() {

       switchself {

       case .one:

           let n =1

       case .two:

           let n =2

       case .three:

           let n =3

// 这里没有default也可以哦,因为enum中的所有值都已经在switch中存在,感觉这样的设计非常的合理

        }

    }

}

至于在其他情况下switch的使用,目前还没有测试到

---------------补充下-----------------

关于swift中的swtich的强大之处在于处理范围匹配和tuple(我更愿意把它们称为多值匹配)

范围匹配支持 ... 和 .. 语法,而不仅仅是 case xx, xxx这样的方式,

而且在支持tuple匹配的时候,在每个tuple里的单个值也可以支持范围匹配。下面给出官方文档中的例子:

“let count = 3_000_000_000_000
let countedThings = "stars in the Milky Way"
var naturalCount: String
switch count {
case 0:
    naturalCount = "no"
case 1...3:
    naturalCount = "a few"
case 4...9:
    naturalCount = "several"
case 10...99:
    naturalCount = "tens of"
case 100...999:
    naturalCount = "hundreds of"
case 1000...999_999:
    naturalCount = "thousands of"
default:
    naturalCount = "millions and millions of"
}”
--------------tuple----------

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


0 0
原创粉丝点击