if
語句後面可以跟一個可選的else
語句,它在if
語句布爾運算式為false
時執行。
語法
Swift 4中if...else
語句的語法如下 -
if boolean_expression {
/* statement(s) will execute if the boolean expression is true */
} else {
/* statement(s) will execute if the boolean expression is false */
}
如果布爾運算式的計算結果為true
,那麼將執行if
代碼塊,否則將執行else
代碼塊。
示例代碼
var varA:Int = 100;
/* Check the boolean condition using if statement */
if varA < 20 {
/* If condition is true then print the following */
print("varA is less than 20");
} else {
/* If condition is false then print the following */
print("varA is not less than 20");
}
print("Value of variable varA is \\(varA)");
編譯並執行上述代碼時,會產生以下結果 -
varA is not less than 20
Value of variable varA is 100