Swift if...else語句

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

上一篇: Swift決策結構 下一篇: Swift迴圈語句