目录

if...else if...else 声明

if语句后面可以跟一个else if...else语句,这对于使用单个if ... else if语句测试各种条件非常有用。

当使用if, else if, else语句时,要记住几点。

  • 一个if可以有零个或一个else的,它必须在任何其他if之后。

  • 一个if可以有零到多个else if是,他们必须在其他之前。

  • 一旦else if成功, else if任何其他else if else不会被测试。

语法 (Syntax)

Swift 4中if...else if...else语句的语法如下 -

if boolean_expression_1 {
   /* Executes when the boolean expression 1 is true */
} else if boolean_expression_2 {
   /* Executes when the boolean expression 2 is true */
} else if boolean_expression_3 {
   /* Executes when the boolean expression 3 is true */
} else {
   /* Executes when the none of the above condition is true */
}

例子 (Example)

var varA:Int = 100;
/* Check the boolean condition using if statement */
if varA == 20 {
   /* If condition is true then print the following */
   print("varA is equal to than 20");
} else if varA == 50 {
   /* If condition is true then print the following */
   print("varA is equal to than 50");
} else {
   /* If condition is false then print the following */
   print("None of the values is matching");
}
print("Value of variable varA is \(varA)");

编译并执行上述代码时,会产生以下结果 -

None of the values is matching
Value of variable varA is 100
↑回到顶部↑
WIKI教程 @2018