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")
}```

你可能感兴趣的:(Swift_循环/分支 结构)