Swift Nested if Statement

Swift 条件语句Swift Conditional Statements

In the Swift language, you can use another if or else if statement inside an if or else if statement.


Syntax

The syntax for a nested if statement in the Swift language is:

if boolean_expression_1 {
   /* 当 boolean_expression_1 表达式 true 时执行 */
   if boolean_expression_2 {
      /* 当 boolean_expression_1 表达式 true 时执行 */
   }
}

You can nestelse if...else, in the same way as nestingifstatements.

Example

import Cocoa

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

/* 检测布尔条件 */
if varA == 100 {
   /* 如果条件为 true 执行以下语句 */
   print("第一个条件为 true");
    
   if varB == 200 {
      /* 如果条件为 true 执行以下语句 */
      print("第二个条件也是 true");
   } 
}
print("varA 变量的值为 \(varA)");
print("varB 变量的值为 \(varB)");

When the above code is compiled and executed, it produces the following result:

第一个条件为 true
第二个条件也是 true
varA 变量的值为 100
varB 变量的值为 200

Swift 条件语句Swift Conditional Statements

Other Extensions