Swift if-else-if Statement
In Swift, the if
, else if
, and else
statements are used for making decisions in your code. These statements allow you to control the flow of your program based on certain conditions.
Syntax
The syntax for the if-else-if statement in Swift is as follows:
if condition1 {
// code to execute if condition1 is true
} else if condition2 {
// code to execute if condition2 is true
} else {
// code to execute if both condition1 and condition2 are false
}
Example
Here is an example of a simple if-else-if statement in Swift:
let num = 10
if num % 2 == 0 {
print("Number is even")
} else if num % 2 != 0 {
print("Number is odd")
} else {
print("Number is neither even nor odd")
}
Output
The output of the above code will be Number is even
, since the num
variable is divisible by 2.
Explanation
In the example above, the if statement checks whether the num
variable is divisible by 2. If it is, then the code inside the if block will be executed, which simply prints the message "Number is even"
to the console.
If the num
variable is not divisible by 2 (i.e. it's odd), then the code inside the else if block will be executed, which prints the message "Number is odd"
.
If both conditions are false, i.e. num
is not even or odd, then the code inside the else block will be executed, which prints the message "Number is neither even nor odd"
.
Use
The if-else-if statement is used in Swift to make decisions in your code based on certain conditions. It allows you to control the flow of your program, and execute different code blocks based on different conditions.
Important Points
- The if-else-if statement is used in Swift for making decisions in your code
- It allows you to control the flow of your program based on certain conditions
- The syntax for the if-else-if statement is:
if condition1 { // code } else if condition2 { // code } else { // code }
- The
else if
andelse
blocks are optional - You can use as many
else if
blocks as you need to check multiple conditions - The first condition that is true will execute its corresponding code block
- If none of the conditions are true, the code in the
else
block will execute
Summary
In summary, the if-else-if statement in Swift allows you to make decisions in your code based on different conditions. It provides a powerful mechanism for controlling the flow of your program, and executing different code blocks based on those conditions. By understanding the syntax and principles of the if-else-if statement, you can write more flexible and responsive code in your Swift applications.