switch的简单使用:

相比 C 和 objective - C 中的 switch 语句,Swift 中的 switch 语句不会默认的掉落到每个 case 的下面进入 另一个 case.相反,第一个匹配的 switch 语句当第一个匹配的 case 一完成, 就完成了它整个的执行。而不需 要一个明确的 break 语句。这使得 switch 语句比在 C 语言中使用更安全、更简单,并避免错误地执行多个 case。

从例子学习:

let anotherCharacter :Character = "a"

switch anotherCharacter {
case "a":
    println("a")
case "A":
    println("The letter is A")
    
default:
    println("NOT letter")
}

通过swift中的playground中可以看到上述代码会输出:"a"

解释一下为什么书"a"字符:在程序中定义一个anotherCharacter常量字符,通过Switch语句中的case进行判断,当与第一个case相遇时发现就是我们想要找得,然后就会执行case中相应的代码块输出"a"字符。

注意:每个case语句至少包含一个可执行语句,否则程序无效

case可以与多个对象进行匹配,之间用逗号隔开:

switch anotherCharacter {
case "b","c","d":
    println("输出bcd")
case "a","e","f":
    println("输出aef")
default:
    println("未找到")
}

//程序会输出:输出aef

因为在执行程序时,与第一个case中的三个对象进行比较判断,发现没有我们想要的,于是紧接着执行第二个case并与其中的多个对象进行比较判断。

Switch中的元组使用:

写一个简单的例子:使用一个点坐标(x,y),表示为一个简单的元组型(Int,Int),并在示例后面的图中将其分类

let OriginPoint = (1, 1)
switch OriginPoint{
case (0,0):
    println("(0,0) is at the origin")
case (_,0):
    println("(\(OriginPoint.0), 0) is on the x-axis")
case (0,_):
    println("(0, \(OriginPoint.1)) is on the y-axis")
case (-2...2,-2...2):
    println("(\(OriginPoint.0), \(OriginPoint.1)) is inside the box")
default:
    println("(\(OriginPoint.0), \(OriginPoint.1)) is outside of the box")
    
}
//输出:"(1, 1) is inside the box"

相应的说明:(_,0)和(0,_)中"_"符号在Swift中代表忽略值得意思;(-2...2,-2...2)中的代表x取值在[-2,2]的区间,y取值在[-2,2]的区间。

posted on 2015-05-15 13:19  奋斗的虫虫  阅读(1819)  评论(0编辑  收藏  举报