推荐答案
在 Swift 中,控制流语句主要包括以下几种:
条件语句:
if
语句if-else
语句if-else if-else
语句switch
语句
循环语句:
for-in
循环while
循环repeat-while
循环
跳转语句:
break
语句continue
语句fallthrough
语句return
语句throw
语句
其他控制流语句:
guard
语句defer
语句
本题详细解读
条件语句
if
语句:用于根据条件执行代码块。如果条件为true
,则执行if
后的代码块。if condition { // 执行代码 }
if-else
语句:如果if
条件为false
,则执行else
后的代码块。if condition { // 执行代码 } else { // 执行其他代码 }
if-else if-else
语句:用于多个条件的判断。if condition1 { // 执行代码 } else if condition2 { // 执行其他代码 } else { // 执行默认代码 }
switch
语句:用于多条件分支选择,比if-else
更简洁。switch value { case pattern1: // 执行代码 case pattern2: // 执行其他代码 default: // 执行默认代码 }
循环语句
for-in
循环:用于遍历集合(如数组、字典)或范围。for item in collection { // 执行代码 }
while
循环:在条件为true
时重复执行代码块。while condition { // 执行代码 }
repeat-while
循环:类似于while
循环,但至少执行一次代码块。repeat { // 执行代码 } while condition
跳转语句
break
语句:用于立即终止循环或switch
语句。while condition { if someCondition { break } }
continue
语句:跳过当前循环的剩余代码,直接进入下一次循环。for item in collection { if someCondition { continue } // 执行代码 }
fallthrough
语句:在switch
语句中,用于继续执行下一个case
的代码。-- -------------------- ---- ------- ------ ----- - ---- --------- -- ---- ----------- ---- --------- -- ------ -------- -- ------ -
展开代码return
语句:用于从函数中返回值并终止函数执行。func someFunction() -> Int { return 42 }
throw
语句:用于抛出错误。throw SomeError.errorCase
其他控制流语句
guard
语句:用于提前退出函数或方法,通常用于条件不满足时。guard condition else { // 执行代码并退出 return }
defer
语句:用于在函数返回前执行某些代码,通常用于资源清理。func someFunction() { defer { // 执行清理代码 } // 执行其他代码 }