Swift - Nested If Statements


Advertisements

It is always legal in Swift 4 to nest if-else statements, which means you can use one if or else ifside another if or else if statement(s).

Syntax

The syntax for a nested if statement is as follows −

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

You can nest else if...else in the similar way as you have nested if statement.

Example

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

/* Check the boolean condition using if statement */
if varA == 100 {
   /* If condition is true then print the following */
   print("First condition is satisfied");

   if varB == 200 {
      /* If condition is true then print the following */
      print("Second condition is also satisfied");
   }
}

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

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

First condition is satisfied
Second condition is also satisfied
Value of variable varA is 100
Value of variable varB is 200
swift_decision_making.htm
Advertisements