Swift – Nested if-else Statement
Last Updated :
11 Sep, 2022
In Swift, a situation comes when we have to check an if condition inside an if-else statement then a term comes named nested if-else statement. It means an if-else statement inside another if statement. Or in simple words first, there is an outer if statement, and inside it another if – else statement is present and such type of statement is known as nested if statement. We can use one if or else if statement inside another if or else if statements.
Syntax:
// Outer if condition
if (condition 1) {
// inner if condition
if (condition 2) {
// Block of Code and Statements
}
// inner else condition
else {
// Block of Code and Statements
}
}
// Outer else statement
else {
// inner if condition
if (condition 3) {
// Block of Code and Statements
}
// inner else condition
else {
// Block of Code and Statements
}
}
Here, if the outer condition1 is true, then it will check for inner condition 2. If inner condition is true then it will proceed to statement 1 otherwise statement 2 will proceed. Similarly in outer else part will execute.
Notes: We can add else and else if statements to the inner if statement whenever required. Also, we can nest multiple layers of if-else statements inside a if statement.
Flowchart:
Example 1:
Swift
import Swift
var a = 100
var b = 200
var c = 300
if (a > b) {
if (a > c ) {
print ( "100 is Greater" )
}
else {
print ( "300 is Greater" );
}
}
else {
if (b > c ) {
print ( "200 is Greater" )
}
else {
print ( "300 is Greater" );
}
}
|
Output:
300 is Greater
Explanation : In above example, First it will check for outer if condition. If outer if condition is true then it will check for inner if statement. If outer if statement is false it then will move to outer else part and so on. Here outer if condition is false. Next it will move to outer else part and check for inner if statement i.e. if b is greater than c ( b > c ). Here it evaluates false. Hence it will move to inner else part and prints statement 4.
Example 2 :
Swift
import Swift
var number = 5
if (number >= 0) {
if (number == 0) {
print ( "Number is 0" )
}
else {
print ( "Number is greater than 0" );
}
}
else {
print ( "Number is smaller than 0" );
}
|
Output :
Number is greater than 0
Explanation : Here we have declared a variable number with value 15. Then we have used if-else construct. If the outer if condition is true then and only then it will execute the inner if condition. In this example, the outer if condition is true hence the inner if block is processed. In the inner if condition, we again have a condition that checks if number is equals to 0 or not. When inner condition is true, then it will process the print statement 1 and If inner if statement is false then it will process the print statement 2. In this case, the inner if condition is false hence it will move to else part and prints statement 2 and the value is printed on the output screen.
Please Login to comment...