Easy Tutorial
❮ Swift Literals Swift Functions ❯

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

Swift Conditional Statements

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:


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

Swift Conditional Statements

❮ Swift Literals Swift Functions ❯