Swift巢狀if語句

2019-10-16 23:14:22

在Swift 4中巢狀if-else語句總是合法的,可以使用ifif else在另一個if,if else,else語句之中。

語法

巢狀if語句的語法如下 -

if boolean_expression_1 {
   /* Executes when the boolean expression 1 is true */

   if boolean_expression_2 {
      /* Executes when the boolean expression 2 is true */
   }
}

可以使用與巢狀if語句類似的方式巢狀if else語句。

範例程式碼

var varA:Int = 100;
var varB:Int = 200;

/* Check the boolean condition using if statement */
if varA == 100 {
   /* 如果條件為真,則列印以下內容 */
   print("First condition is satisfied");

   if varB == 200 {
      /*如果條件為真,則列印以下內容 */
      print("Second condition is also satisfied");
   }
}

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

編譯並執行上述程式碼時,會產生以下結果 -

First condition is satisfied
Second condition is also satisfied
Value of variable varA is 100
Value of variable varB is 200