一,OC中的Switch语句
1、switch语句分支必须是整数
2、每个语句都需要一个break
3、如果要穿透,case连着写。 如:case 9: case 10:
二,Swift中的switch:
1、可以针对任意类型的值进行分支,不再局限于整数。(重)
2、一般不需要break。
3、如果使用多值,使用 ,
4、所有分支至少有一条指令。如果什么都不做,才直接使用break.
func demo(str: String) {
switch str {
case "10":
print("A")
case "9":
print("B")
//借助 , 执行多个分支
case "8","7":
print("C")
case "6":
//什么都不做,使用break
break
default:
print("D")
}
}
注意:每一个case后面必须有可执行的语句
什么都不写的话,会报这个错误
case 后面可以填写一个范围匹配
let score = 95
switch socre {
case 90...100:
println("A")
case 60...89:
println("B")
default:
println(C)
switch
要保证处理所有可能的情况 不然编译器会报错
因此 这里的default
一定要加 不然会出现一些处理不到的情况
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 的数值绑定
在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 的用法
执行完当前的case后 会执行fallthrogh 后面的的case
或者default
let num = 20
var str = "\(num)是个"
switch num{
case 0...50:
str += "0~50之间的"
fallthrough
default:
str += "整数"
}
println(str)
//打印 : 20 是个0~50之间的整数
注意:fallthrough后面的case条件不能定义变量和常量
把let放在外面和放在里面为每一个元素单独写上let是等价的。
当你在一个case里使用Value Binding的时候,如果你同时也在它的上一个case里使用了fallthrough,这是编译器所不允许的,你可能会收到这样一个编译错误: