Latest web development tutorials

Swift if ... else if ... else statement

Swift conditional statement Swift conditional statement

After aif statement with an optional else if ... else statement,else if ... elsestatementin the test more than one condition statement is very useful.

When you use if, else if, else needs to note the following statement:

  • Can have zero or one else after the if statement, but if else if statement, else statement else if needed after the statement.
  • Can have zero or more statements after the if statement else if, else if statement must appear before the else statement.
  • Once else statement executed successfully, the other or else if else statements are not executed.

grammar

if boolean_expression_1 {
   /* 如果 boolean_expression_1 表达式为 true 则执行该语句 */
} else if boolean_expression_2 {
   /* 如果 boolean_expression_2 表达式为 true 则执行该语句 */
} else if boolean_expression_3 {
   /* 如果 boolean_expression_3 表达式为 true 则执行该语句 */
} else {
   /* 如果以上所有条件表达式都不为 true 则执行该语句 */
}

Examples

import Cocoa

var varA:Int = 100;

/* 检测布尔条件 */
if varA == 20 {
    /* 如果条件为 true 执行以下语句 */
    print("varA 的值为 20");
} else if varA == 50 {
    /* 如果条件为 true 执行以下语句 */
    print("varA 的值为 50");
} else {
    /* 如果以上条件都为 false 执行以下语句 */
    print("没有匹配条件");
}
print("varA 变量的值为 \(varA)");

When the above code is compiled executed, it will produce the following results:

没有匹配条件
varA 变量的值为 100

Swift conditional statement Swift conditional statement