Swift – If-else-if Statement
Last Updated :
11 Sep, 2022
In Swift, the if-else if-else condition is used to execute a block of code among multiple options. It gives a choice between more than two alternative conditions as soon as one of the conditions is true, the statement associated with that if is executed. If all conditions are false or not satisfied then the final else statement will be executed in the program.
Syntax:
if (condition1){
// Block of code and Statements
}
else if (condition2){
// Block of code and Statements
}
else if (condition3){
// Block of code and Statements
}
.
.
.
else {
// Block of code and Statements
}
Here, If condition1 is true, then statement 1 is executed. If condition1 is false, then it will go to else if statement and evaluate condition 2. If condition 2 is true, statement 2 will be executed. If condition 2 is false, then it will go to else if statement and evaluate condition 3 likewise so on. If neither condition is true it will move to the else part and then the final else statement will be executed.
Flowchart:
Example 1: Swift program illustrate the use of if-else-if statement.
Swift
let number = 85
if (number >= 90){
print ( "Grade A" )
}
else if (number >= 75) {
print ( "Grade B" )
}
else if (number >= 60) {
print ( "Grade c" )
}
else {
print ( "Grade D" )
}
|
Output:
Grade B
Explanation: In the above example, first we create a variable named “number”. Now using the if-else-if statement we check if the number is greater than or equal to 90, assigning grade A. Or if the number is greater than or equal to 75, assign grade B. Or if the number is greater than or equal to 60, assign grade C. So here the output will be Grade B because number = 85 which satisfies the condition “number is greater than or equal to 75”.
Example 2:
Swift
let number = 20
if (number == 10){
print ( "Number is 10" )
}
else if (number == 15){
print ( "Number is 15" )
}
else if (number == 20){
print ( "Number is 20" )
}
else {
print ( "Number is not present" )
}
|
Output:
Number is 20
Explanation: In the above example, we created a variable that holds an expression and we have three condition expressions:
- if (number == 10) : checks if number equal to 10
- else if (number == 15) : checks if number is equal to 15.
- else if (number == 20) : checks if number is equal to 20.
Here, both conditions1 and condition2 are false. Hence the statement will move to condition3(condition3 is true) and statement 3 is executed.
Please Login to comment...