Swift_循環/分支 結構

一. 常用循環結構

循環: for, for_in, while, repeat_while

for循環

// 不需要添加括號
for var i = 0; i < 10; i++ {
    
 >   print(i)

>}```

>####forin循環

//1..<10: 表示開區間, 即1~9
for var number in 1..<10{

print(number)

}

//1...10: 表示閉區間, 即1~10
for var number in 1...10{

print(number)

}```

while循環

var j = 5
while j > 0{
    j--
    print(j)
}```

>####repeat_while(即: OC 中的do...while循環)

var i = 10
repeat {

print("repeat")
i--

}while i > 0```

循環遍歷數組

var animal = ["a", "b", "c", "d", "e"]
for a in animal{
    
>    print(a)
}```

>####循環遍歷字典

animalDic = ["dog":"??", "cat":"??"]
//注意: 結果的參數類型
for (key, value) in animalDic{

print("key = (key), value = (value)")
}```

二. 常用的分支結構

  1. if , if ... else , switch...case

if, if ... else

>let flag:Bool = true
if flag == true{
    
  >  print("flage = \(flag)")
    
>}else{
    
>    print("flage = ", false)
}```

>####2. switch ... case ( 默認自帶 break)

//特點:
//1. switch中想要實現貫穿, 使用關鍵字fallthrough
let temp = 20
switch temp {

case 0 : print("為零")
fallthrough
case 1 : print("為1")
fallthrough
default : print("你猜")
}

//2. case 后面可以是條件范圍
switch temp {
case var a where temp >= 0 && temp < 10 :
a = 20
print("a = (a)")
default : print("你猜")

}

//3. case后面可以是添加范圍
switch temp {
case 0...10 :
print("0~9")
case 10...20:
print("10~20")
default : print("你猜")

}

//4. switch ... case 可以匹配一個元組
let point = (10, 10)
switch point {

case (10, 0):
print("case1")
case (0, 10):
print("case2")
case (10, 10):
print("case3")

default:
print("other")
}```

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容