Swift if語句

2019-10-16 23:14:17

if語句由一個布林表示式後跟一個或多個語句組成。

語法

Swift 4中if語句的語法如下 -

if boolean_expression {
   /* statement(s) will execute if the boolean expression is true */
}

如果布林表示式(boolean_expression)的計算結果為true,那麼將執行if語句中的程式碼塊。 如果布林表示式的計算結果為false,則將執行if語句結束後(在結束大括號之後)的第一組程式碼。

範例程式碼

var varA:Int = 10;

/* 使用if語句檢查布林條件 */
if varA < 20 {
   /* 如果條件為真,則列印以下內容 */
   print("varA is less than 20");
}

print("Value of variable varA is \(varA)");

當使用playground執行上述程式時,得到以下結果 -

varA is less than 20
Value of variable varA is 10