Swift - if...else if...else Statement


An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.

When using if, else if, else statements, there are a few points to keep in mind.

Syntax

The syntax of an if...else if...else statement in Swift 4 is as follows −

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

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

} else if boolean_expression_3 {
   /* Executes when the boolean expression 3 is true */

} else {
   /* Executes when the none of the above condition is true */
}

Example

Live Demo
var varA:Int = 100;

/* Check the boolean condition using if statement */
if varA == 20 {
   /* If condition is true then print the following */
   print("varA is equal to than 20");

} else if varA == 50 {
   /* If condition is true then print the following */
   print("varA is equal to than 50");

} else {
   /* If condition is false then print the following */
   print("None of the values is matching");
}

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

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

None of the values is matching
Value of variable varA is 100
swift_decision_making.htm