Swift嵌套if语句

在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

上一篇: Swift决策结构 下一篇: Swift循环语句