switch的簡單使用:swift
相比 C 和 objective - C 中的 switch 語句,Swift 中的 switch 語句不會默認的掉落到每一個 case 的下面進入 另外一個 case.相反,第一個匹配的 switch 語句當第一個匹配的 case 一完成, 就完成了它整個的執行。而不需 要一個明確的 break 語句。這使得 switch 語句比在 C 語言中使用更安全、更簡單,並避免錯誤地執行多個 case。安全
從例子學習:ide
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"字符。spa
注意:每一個case語句至少包含一個可執行語句,不然程序無效對象
case能夠與多個對象進行匹配,之間用逗號隔開:blog
switch anotherCharacter { case "b","c","d": println("輸出bcd") case "a","e","f": println("輸出aef") default: println("未找到") } //程序會輸出:輸出aef
由於在執行程序時,與第一個case中的三個對象進行比較判斷,發現沒有咱們想要的,因而緊接着執行第二個case並與其中的多個對象進行比較判斷。it
Switch中的元組使用:class
寫一個簡單的例子:使用一個點座標(x,y),表示爲一個簡單的元組型(Int,Int),並在示例後面的圖中將其分類object
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]的區間。