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