//OC 中在 case 中定义变量要加 { }
int a = 13;
switch (a) {
default:
NSLog(@"默认");
break;
case 2:
NSLog(@"sdfa");
break;
case 10:
{ //在 case 中定义变量要加 { }
int c = 20;
NSLog(@"%d",c);
}
break;
}
Swift 中 case 不要加小括号 (),而 OC 中需要;
Swift 中 case 后面可以有多个判断条件,而 OC 后面只能有 1 个判断条件;
Swift 中 每个 case 语句结束后不需要加 break,其默认是不穿透,如果需要穿透就加 fallthrough 语句;而 OC 默认穿透,每个 case 语句结束要加 break;
//MARK : switch 语句
let a = 10.1
func testSwitch(x:Double)
{
switch x {
case 10.1:
print("参数为\\(x)")
fallthrough
case 5,10.1:
print("参数为5或者10.1")
default:
print("不知道")
}
}
testSwitch(x: a)
四、switch 语句的特殊使用方法
取值范围表示:
var x in 1...10 表示为 1 <= x <= 10
var x in 1..<10 表示为 1 <= x < 10
//MARK - switch 语句的特殊使用方法
func testSwitch01(score:Int)
{
switch score {
case 0..<425:
print("六级没过")
case 425..<700:
print("分数很高")
case 700:
let fallScore = 725
print("快接近满分啦,满分为\\(fallScore)")
default:
print("不知道")
}
}
testSwitch01(score: 700)
switch 中元组的使用:
Swift 语句中,区间可以为 double;
可以进行值绑定。
//元祖(以点坐标为例)
func testSwitch02(point:(x:Double,y:Double))
{
switch point {
case (0,0):
print("点在原点")
case (1...10.6,1...10):
print("点在第一象限")
case (_,0):
print("点在 X 轴上")
case (0,let y): //值绑定
print("在y轴上 \\(y) 位置")
case let(x,y) where x>y: //根据条件绑定
print("在 y=x 直线下方,具体点位置为(\\(x),\\(y))")
case let(x,y) where x<y:
print("点在 y=x 上方,具体点位置为(\\(x),\\(y))")
default:
print("不知道")
}
}
testSwitch02(point: (-40.1,-5))