Swift Nested if Statements
In Swift, you can use an if or else if statement inside another if or else if statement.
Syntax
The syntax for nested if statements in Swift:
if boolean_expression_1 {
/* Executed when boolean_expression_1 is true */
if boolean_expression_2 {
/* Executed when boolean_expression_2 is true */
}
}
You can nest else if...else in a similar way to nesting if statements.
Example
import Cocoa
var varA:Int = 100;
var varB:Int = 200;
/* Check the boolean condition */
if varA == 100 {
/* Execute the following statement if the condition is true */
print("The first condition is true");
if varB == 200 {
/* Execute the following statement if the condition is true */
print("The second condition is also true");
}
}
print("The value of varA is \(varA)");
print("The value of varB is \(varB)");
When the above code is compiled and executed, it produces the following result:
The first condition is true
The second condition is also true
The value of varA is 100
The value of varB is 200