第五章:控制流

254 阅读2分钟

1.1 for循环

当不需要知道每次循环时变量的值时,可以使用下划线_来代替变量名。

for _ in 0...5 {
    print("循环")
}

for条件递增循环的格式为:

for initialization; condition; increment {
    statements
}

1.2 while循环

while循环就是重复执行一系列语句,直到条件语句值为false。 while循环的格式为:

while condition {
    statements
}

repeat-while循环的格式为:

repeat {
    statements
} while condition

1.3 if条件语句

if条件语句的格式为:

if condition1 {
    statements
} else if condition2 {
    statements
} else {
    statements
}

1.4 switch条件语句

switch语句的格式如下:

switch someValue {
    case value1: statementsFor1
    case value2, value3: statementsFor23
    default: statementsDefault
}

当第一次与某个case条件匹配,执行该case中对应的语句后,就直接跳出并执行switch块的后续语句,而不会继续与其他case条件进行比较。这一点与 C 语言的差别。在 C 语言中,需要显式的使用break跳出switch块。

switch语句中case部分的条件也可以是一个范围。

var curMonth: Int

curMonth = 3

switch curMonth {
case 1...2:
    print("1-2")
case 3...5:
    print("3-5")
default:
    print("none")
}

swith语句也可以对元祖进行值的匹配。

let yearClass = (2020, "Swift")

switch yearClass {
case (2019, "Swift"):
    print("2019-Swift")
case (2020, _):
    print("2020-any")
case (2020, "Swift"):
    print("2020-Swift")
default:
    print("none")
}

// 输出结果为“2020-any”,当和第一个条件匹配成功后,就跳出switch比较

switch语句中的case可以进行值绑定,即:将某个case匹配的值绑定到一个临时的变量或常量上,然后在该case的执行语句中就可以引用绑定的变量或常量了。

let yearClass = (2020, "Swift")

switch yearClass {
// 值绑定,虽然三个case都满足,但是第一个满足后就不再比较
case let (x, y) where x == 2020:
    print(x, y)
case (2020, let y):
    print("2020-any")
case (2020, "Swift"):
    print("2020-Swift")
default:
    print("none")
}

1.5 控制转移语句

常用的控制转移语句:continue语句、break语句。

continue语句在循环语句中使用,当执行continue语句时,本次循环结束,继续下一个循环的执行。

当执行break语句时,直接终止当前控制流,并跳到控制流以外的后续语句处继续执行。