Swift系列5-控制流

For-in循环

使用for-in来遍历数据,数组,字典,范围数字,字符串等

1
2
3
4
5
6
7
8
9
10
//遍历数组
let myArr:Array = ["1","2","3","4","5","6","7","8","9","0"]
for (index,item) in myArr.enumerated() {
print("\(index)下标的值是\(item)")
}

//遍历区间
for i in 1...5 {
print(i)
}

while循环,Repeat-While

1
2
3
4
5
6
7
8
9
10
//while循环:循环通过某个单一的条件,当条件为false时,跳出循环
var i = 5
while i < 10 {
i = i + 1
}
//repeat-while:判断之前,先执行一次代码,然后判断条件,直到条件为false,跳出循环
repeat {
print(i)
i = i + 1;
}while i < 20

条件语句(if,switch)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//if:执行单一的if条件,为true才执行里面的语句;false则执行另外一个语句
let a = 10
let b = arc4random() % 20
if a >= b {
print("a大于或者等于b")
}else{
print("b大于a")
}
//多个条件判断时,使用else if
if a == b {
print("a = b")
}else if(a > b){
print("a > b")
}else{
print("a < b")
}
//switch:多个条件判断语句,case之后必须至少有一条可执行的语句,否则会编译不过;
let c = arc4random() % 50
switch c {
case 12:
print("12")
case 22:
print("22")
case 33:
print("33")
default:
print("所有条件都没有匹配到")
}

continue,break,return,fallthrough

continue:循环语句中跳出这一次循环(continue后面的语句不会被执行),执行下一次循环

1
2
3
4
5
6
7
8
for g in [1,2,3,4,5,6] {
print("before \(g)") //结果:1 2 3 4 5 6
if g == 2 {
continue
}
print("当g == 2时,不会执行这之后的语句\(g),而是直接执行g == 3,4,5,6")
print("after \(g)") //结果:1 3 4 5 6
}

break:循环语句中,跳出整个循环

1
2
3
4
5
6
7
8
for j in 1...3 {
print("before \(j)") // 1,2
if j == 2 {
break
}
print("before \(j)") // 1
}
print("end 不会执行到j == 3")

return:函数返回,不会再执行后面的语句

1
2
3
4
5
6
7
8
func getOne(){
print("before")
let i = arc4random() % 10
if i == 3 {
return
}
print("after")//当i == 3函数已经返回,这句及后面的语句都不会再执行
}

fallthrough:在switch语句中 执行了符合条件的case之后,如果要执行后面一个语句需要用fallthrough来贯穿

1
2
3
4
5
6
7
8
let r1 = arc4random() % 10
switch r1 {
case 4:
print("4")
fallthrough
default:
print("done")//添加了fallthrough 该语句也会被执行
}

检查API的可用性

1
2
3
4
5
6
7
8
if #available(iOS 11, *) {
//API在iOS11之后才可用
}
//修饰方法
@available(iOS 13.0, *)
func getName(){
//表示该方法iOS13之后才可用
}

The end