Swift if...else語句

2019-10-16 23:14:19

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