Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift if…else if…else Statement

Swift if...else if...else Statement

Swift conditional statementsSwift Conditional Statements

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:


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 statementsSwift Conditional Statements