Introduction
In this blog, we will learn how to use the Swift if-else statement to create decision-making programmes using examples.
When employing otherwise if, else sentences, there are a few things to bear in mind.
An if can have a value of zero or one, and it must come after any other ifs.
An if can have one or more else ifs, which must come before the else.
Once an else succeeds, none of the other else ifs or else are tested.
Let's move forward to knowing what if-else statements are and how to use them in Swift to create decision-making programs.
If-else Statement
When one or more meeting criteria are met, an if statement is used to run the code, and a piece of information can take one of two forms. The opening and closing braces are required in each form.
The first form permits code execution only when a condition is met.
In computer programming, the if Statement is used to run a piece of code only when a specified condition is met.
For example, assigning grades (A, B, C) based on marks obtained by a student.
1. if the percentage is above 90, give a grade A
2. if the rate is above 75, give a grade of B
3. if the rate is above 65, give a grade of C
Syntax of if Statement in Swift
Swift's if statement syntax is as follows:
if (condition) {
// statements
}
The if statement evaluates the condition contained within the parenthesis ().
If the condition is met, the code contained within the if the body is run.
If the condition is false, the code contained within the if statement is skipped.
First Form
The first form, which has the following syntax, allows code to be executed only when a condition is met:
if condition {
statements
}
Second Form
The second form of an if statement adds an else clause (initiated by the else keyword) and is used to execute one part of code when the condition is true and another part of code when the condition is false. When there is only one else clause, an if statement takes the following form:
if condition {
If the condition is true, statements will be executed. }
else {
If the condition is false, statements will be executed. }
Third Form
An if statement's else clause can contain another if statement to test more than one condition. An if statement chained in this manner takes the following form:
if condition 1 {
If the condition is true, statements will be executed. }
else if condition 2 {
If the condition is true, statements will be executed. }
else {
If the condition is false, statements will be executed. }