Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Nested if Statement

Swift Nested if Statement

Swift conditional statementsSwift Conditional Statements

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


Syntax

Syntax of nested if statements in Swift:



if boolean_expression_1 {

   /* Execute when boolean_expression_1 is true */

   if boolean_expression_2 {

      /* Execute when boolean_expression_1 is true */

   }

}

You can nest else if...else, in the same way as nesting if statements.

Example



import Cocoa



var varA:Int = 100;

var varB:Int = 200;



/* Check boolean condition */

if varA == 100 {

   /* If the condition is true, execute the following statements */

   print("第一个条件为 true");

    

   if varB == 200 {

      /* If the condition is true, execute the following statements */

      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 conditional statementsSwift Conditional Statements