Swift if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is very useful for testing multiple conditions.
When using if, else if, else statements, keep the following points in mind:
- An if statement can have 0 or 1 else, and it must come after any else if statements.
- An if statement can have 0 or more else if statements, which must come before the else statement.
- Once an if statement executes successfully, none of the other else if or else statements will execute.
Syntax
if boolean_expression_1 {
/* Execute this statement if boolean_expression_1 is true */
} else if boolean_expression_2 {
/* Execute this statement if boolean_expression_2 is true */
} else if boolean_expression_3 {
/* Execute this statement if boolean_expression_3 is true */
} else {
/* Execute this statement if none of the above conditions are true */
}
Example
import Cocoa
var varA:Int = 100;
/* Check the boolean condition */
if varA == 20 {
/* Execute this statement if the condition is true */
print("The value of varA is 20");
} else if varA == 50 {
/* Execute this statement if the condition is true */
print("The value of varA is 50");
} else {
/* Execute this statement if none of the above conditions are true */
print("No matching condition");
}
print("The value of varA is \(varA)");
When the above code is compiled and executed, it produces the following result:
No matching condition
The value of varA is 100