一個 if 語句可以跟著一個可選的 else 語句,當(dāng)布爾表達(dá)式為假時,else 語句塊執(zhí)行。
一個 if ... else 語句在 Swift 中的語法如下:
if boolean_expression {
/* statement(s) will execute if the boolean expression is true */
} else {
/* statement(s) will execute if the boolean expression is false */
}
如果布爾表達(dá)式的值為true,那么 if 代碼塊將被執(zhí)行,否則 else 代碼塊將被執(zhí)行。

var varA:Int = 101;
/* Check the boolean condition using if statement */
if varA < 20 {
/* If condition is true then print the following */
println("varA is less than 20");
} else {
/* If condition is false then print the following */
println("varA is not less than 20");
}
println("Value of variable varA is \(varA)");
當(dāng)上述代碼被編譯和執(zhí)行時,它產(chǎn)生了以下結(jié)果:
varA is not less than 20 Value of variable varA is 101