一. 常用循環(huán)結(jié)構(gòu)
循環(huán): for, for_in, while, repeat_while
for循環(huán)
// 不需要添加括號
for var i = 0; i < 10; i++ {
> print(i)
>}```
>####forin循環(huán)
//1..<10: 表示開區(qū)間, 即1~9
for var number in 1..<10{
print(number)
}
//1...10: 表示閉區(qū)間, 即1~10
for var number in 1...10{
print(number)
}```
while循環(huán)
var j = 5
while j > 0{
j--
print(j)
}```
>####repeat_while(即: OC 中的do...while循環(huán))
var i = 10
repeat {
print("repeat")
i--
}while i > 0```
循環(huán)遍歷數(shù)組
var animal = ["a", "b", "c", "d", "e"]
for a in animal{
> print(a)
}```
>####循環(huán)遍歷字典
animalDic = ["dog":"??", "cat":"??"]
//注意: 結(jié)果的參數(shù)類型
for (key, value) in animalDic{
print("key = (key), value = (value)")
}```
二. 常用的分支結(jié)構(gòu)
- 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 ( 默認(rèn)自帶 break)
//特點(diǎn):
//1. switch中想要實(shí)現(xiàn)貫穿, 使用關(guān)鍵字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 可以匹配一個(gè)元組
let point = (10, 10)
switch point {
case (10, 0):
print("case1")
case (0, 10):
print("case2")
case (10, 10):
print("case3")
default:
print("other")
}```