Swift if...else if...else Statement
A if statement An if statement can be followed by an optional else if...else Statement,else if...else Statement is very useful when testing multiple conditional statements.
When using if, else if, and else statements, keep the following points in mind:
- An if statement can be followed by 0 or 1 else, but if there are else if statements, the else statement must come after the else if statements.
- An if statement can be followed by 0 or more else if statements, and else if statements must appear before any else statement.
- Once an if statement executes successfully, no other else if or else statements will execute.
Syntax
if boolean_expression_1 {
/* If boolean_expression_1 is true, execute this statement */
} else if boolean_expression_2 {
/* If boolean_expression_2 is true, execute this statement */
} else if boolean_expression_3 {
/* If boolean_expression_3 is true, execute this statement */
} else {
/* If none of the above condition expressions are true, then execute this statement */
}
Example
import Cocoa
var varA:Int = 100;
/* Check boolean condition */
if varA == 20 {
/* If the condition is true, execute the following statements */
print("varA 的值为 20");
} else if varA == 50 {
/* If the condition is true, execute the following statements */
print("varA 的值为 50");
} else {
/* If all the above conditions are false, execute the following statements */
print("没有匹配条件");
}
print("varA 变量的值为 \(varA)");
When the above code is compiled and executed, it produces the following result:
没有匹配条件
varA 变量的值为 100
Swift Conditional Statements