一隔箍,OC中的Switch語句
1、switch語句分支必須是整數(shù)
2脚乡、每個語句都需要一個break
3蜒滩、如果要穿透,case連著寫。 如:case 9: case 10:
二奶稠,Swift中的switch:
1俯艰、可以針對任意類型的值進行分支,不再局限于整數(shù)锌订。(重)
2竹握、一般不需要break。
3辆飘、如果使用多值啦辐,使用 ,
4、所有分支至少有一條指令蜈项。如果什么都不做昧甘,才直接使用break.
func demo(str: String) {
switch str {
case "10":
print("A")
case "9":
print("B")
//借助 , 執(zhí)行多個分支
case "8","7":
print("C")
case "6":
//什么都不做,使用break
break
default:
print("D")
}
}
注意:每一個case后面必須有可執(zhí)行的語句
什么都不寫的話战得,會報這個錯誤
case 后面可以填寫一個范圍匹配
let score = 95
switch socre {
case 90...100:
println("A")
case 60...89:
println("B")
default:
println(C)
switch
要保證處理所有可能的情況 不然編譯器會報錯
因此 這里的default
一定要加 不然會出現(xiàn)一些處理不到的情況
Value Binding
針對元組,Switch還支持類似于Optional Binding的Value Binding庸推,就是能把元組中的各個值提取出來常侦,然后直接在下面使用:
let request = (0,"success")
switch request {
case (0, let state):
state //被輸出:success
case (let errorCode, _):
"error code is \(errorCode)"
} // 涵蓋了所有可能的case,不用寫default了
這樣也是可以的:
let request = (0,"success")
switch request {
case let (errorCode, state):
state //被輸出:success
case (let errorCode, _):
"error code is \(errorCode)"
}
case 還可以匹配元組
這是與OC 一個不一樣的地方 方便使用
let point = (1,1)
switch point{
case (0,0):
println("這個點在原點上")
case (_,0):
println("這個點在x軸上")
case (0,_):
println("這個點在y軸上")
case (-2...2,-2...2)
println("這個點在矩形框內")
case 的數(shù)值綁定
在case匹配的同時 可以講switch中的值綁定給一個特定的變量或者常量
以便在case后面的語句中使用
let point = (10,0)
switch point{
case (let x,0):
println("這個點在x軸上贬媒,x值是\(x)")'
case (0,let y):
println("這個點在y軸上聋亡,y的值是\(y)")
case let (x,y):
printf("這個點的x值是\(x),y值是\(y)")
}
//打印:這個點在x 軸上 x 值是(y)
注意觀察 這里是沒有default 的 所有default不是必須的
但是case 必須處理所有的情況
where 這個語法是特別好用的 比以前的判斷簡單多了
switch 語句可以使用where 來增加判斷條件
//比如判斷一個點是否在一條線上
var point = (10,-10)
switch point{
case let (x,y) where x == y:
println("這個點在綠色的線上")
case let (x,y) where x == -y:
println("這個點在紫線上")
default :
printf("這個點不在這兩條線上")
}
fallthrough 的用法
執(zhí)行完當前的case后 會執(zhí)行fallthrogh 后面的的case
或者default
let num = 20
var str = "\(num)是個"
switch num{
case 0...50:
str += "0~50之間的"
fallthrough
default:
str += "整數(shù)"
}
println(str)
//打印 : 20 是個0~50之間的整數(shù)
注意:fallthrough后面的case條件不能定義變量和常量
把let放在外面和放在里面為每一個元素單獨寫上let是等價的际乘。
當你在一個case里使用Value Binding的時候坡倔,如果你同時也在它的上一個case里使用了fallthrough,這是編譯器所不允許的,你可能會收到這樣一個編譯錯誤: