在Swift 4中嵌套if-else
語句總是合法的,可以使用if
或if 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