Swift支持的流程控制
循環(huán)結(jié)構(gòu):for 、 for-in 、 while 炊昆、 do-while
選擇結(jié)構(gòu):if 敏晤、 switch
注意點: 這些語句后面一定要跟上大括號{}
跟c語言基本一樣的有
for 贱田、 if 、 while 嘴脾、 do-while
不一樣的有for-in和switch
for-in
(1):for-in
for i in 0...3
{
}
若可以不使用i,可以像下面這樣寫
for _ in 0...3
{
}
switch
注意點:
swift語句中不使用break湘换,在執(zhí)行完case里面的代碼以后就會退出switch;
switch要保證出力所有可能的情況,不然編譯報錯
2.1:每一個case里面必須有可以執(zhí)行的語句;
2.2:case的多條件匹配
case后面可以填寫多個匹配條件,條件之間用逗號隔開
let score = 96;
switch score{
case 90,91,92
print("優(yōu)秀")
case 60,,7080:
print("及格")
default:
print("不及格")
}
2.3:case的多條件匹配范圍
let score = 96;
switch score{
case 90...10
print("優(yōu)秀")
case 60...80:
print("及格")
default:
print("不及格")
}
2.4:匹配元祖
let point = (1,1);
switch point {
case (0,0):
print("點在原點上")
case (_,0):
print("點在x軸上")
case (0,_):
print("點在y軸上")
case (-2...2,-2...2):
print("x在-2到2之間统阿,y在-2到2之間")
default:
print("其他");
//下劃線代表忽略這個值,也可以代表是任何值都可以
}
2.5:數(shù)值的綁定
在case匹配的同時筹我,可以將siwtch中的值綁定給一個特定的常量或者變量扶平,一邊在case后面的語句中使用;
let point = (10,0);
switch point {
case (let x,0):
print("這個點在x軸上蔬蕊,x的值\(x)")
case (0,let y):
print("這個點在y軸上结澄,y的值\(y)")
case (let x,let y):
print("這個點在x的值\(x),在y軸上的值\(y)")
}
2.6:switch可以使用where來增加判斷的條件
var point = (10,-10)
switch point {
case let(x,y) where x == y:
print("------")
case let(x,y) where x == -y:
print("======")
default:
print("其他")
}
fallthrough的作用
執(zhí)行完當前的case后,會接著執(zhí)行fallthrough后面的case或者default
let num = 20
var string = "\(num)是個"
switch num {
case 0...50:
string += "0~50之間的"
fallthrough
default:
string += "整數(shù)"
}
注意點: fallthrough后面不能定義變量和常量
var point = (10,10)
switch point {
case (0...10,0...10):
print("------")
case let(x,y) where x==y
print("---------")//錯誤的
default:
print("xxxxxx")
}
標簽
使用標簽的其中一個作用:可以用于指定要退出哪一個循環(huán)
for _ in 0...1 {
for _ in 0...2 {
print("鍛煉身體")
break //退出內(nèi)層循環(huán)
}
print("休息十分鐘")
}
group: for _ in 0...1 {
for _ in 0...2 {
print("鍛煉身體")
break group //執(zhí)行一次就跳出外層循環(huán)
}
print("休息十分鐘")
}
guard的使用
guard 表達式 else
1:當條件表達式為ture時岸夯,執(zhí)行語句組中的內(nèi)容麻献,跳過else語句中的內(nèi)容;
2:當條件表達式為false時,執(zhí)行else語句中的內(nèi)容猜扮,跳轉(zhuǎn)語句一般是return(函數(shù)中使用)勉吻、break(循環(huán)中使用)、continue(循環(huán)中使用)和throw
guard 條件表達式 else{
//條件語句
break
}
語句組
例子
var age = 20;
func online(age:Int)->void{
guard age <= 10 else{
print"青鉤子娃兒"
break;
}
print("你已不再年輕")
}
online(age)
swift中的do while循環(huán)需要寫成 repeat while
var a = 10
repeat{
print(a)
a -= 1
}while a > 0