×

Swift if..else if..else Statement


if..else if..else Statement

Swift if..else if..else is used to check mutliple conditions if previous if block condition is not satisfied.

Syntax :-

if(condition 1)
{
  
}
else if (condition 2)
{

}
else 
{

}

Example :-

import UIKit

var a:Int = 4


if(a > 5)
{
    print("a is greater than 5")
}
else if(a < 5)
{
print("a is less than 5")
}
else
{
 print("Try for another value")
}

Output :-

a is less than 5

In this swift program we first initialised a variable 'a' with value '4' . Then if condition checks wether 'a is greater than 4' or not . Since value is not greater , block inside first if is not executed. Then control flows to else if block. And since value of 'a' is less than 5 , block inside second else if condition is executed. That's why output 'a is less than 5' .