Swift if...else if...else语句

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

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

  • 一个if可以有零个或一个else语句,它必须在else...if之后。
  • if可以有零或多个else...if语句,并且它们必须在else语句之前。
  • 当有一个if...else匹配成功,其余的else...if或者else语句都不会被测试。

语法

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 */
}

示例代码

var varA:Int = 100;

/* 使用if语句检查布尔条件 */
if varA == 20 {
   /* 如果条件为真,则打印以下内容 */
   print("varA is equal to than 20");

} else if varA == 50 {
   /* 如果条件为真,则打印以下内容 */
   print("varA is equal to than 50");

} else {
   /* 如果条件为假,则打印以下内容 */
   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

上一篇: Swift决策结构 下一篇: Swift循环语句