取決于一個或者多個條件的值,分支語句允許程序執(zhí)行指定部分的代碼。顯然,分支語句中條件的值將會決定如何分支以及執(zhí)行哪一塊代碼。Swift 提供兩種類型的分支語句:if語句和switch語句。
switch語句中的控制流可以用break語句修改,詳情請見Break 語句。
取決于一個或多個條件的值,if語句將決定執(zhí)行哪一塊代碼。
if語句有兩種標準形式,在這兩種形式里都必須有大括號。
第一種形式是當且僅當條件為真時執(zhí)行代碼,像下面這樣:
if
condition{
statements
}
第二種形式是在第一種形式的基礎(chǔ)上添加 else 語句,當只有一個 else 語句時,像下面這樣:
if
condition{statements to execute if condition is true} else {statements to execute if condition is false}
同時,else 語句也可包含if語句,從而形成一條鏈來測試更多的條件,像下面這樣:
ifcondition 1{
statements to execute if condition 1 is true
} else ifcondition 2{
statements to execute if condition 2 is true
}
else {
statements to execute if both conditions are false
}
if語句中條件的值的類型必須遵循LogicValue協(xié)議。同時,條件也可以使用可選綁定,詳情參見可選綁定。
If語句語法
if語句 → if if條件 代碼塊 else子句(Clause) 可選
if條件 → 表達式 | 聲明
else子句(Clause) → else 代碼塊 | else if語句
取決于switch語句的控制表達式(control expression),switch語句將決定執(zhí)行哪一塊代碼。
switch語句的形式如下:
switchcontrol expression{
casepattern 1:
statements
casepattern 2wherecondition:
statements
casepattern 3wherecondition,
pattern 4where上一篇:Swift布爾值下一篇:Swift 下標