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

Swift if…else Statement

Swift if...else Statement

Swift conditional statementsSwift Conditional Statements

A if statement An if statement can be followed by an optional else statement, the else statement executes when the Boolean expression is false.

Syntax

In the Swift language if...else statement syntax:



if boolean_expression {

   /* statement to execute if the boolean expression is true */

} else {

   /* statement to execute if the boolean expression is false */

}

If the Boolean expression is true, then the if block's code is executed. If the Boolean expression is false, then the else block's code.

Flowchart

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 {

   /* 如果条件为 false 执行以下语句 */

   print("varA 大于 20");

}

print("varA 变量的值为 \(varA)");

When the above code is compiled and executed, it produces the following result:



varA 大于 20

varA 变量的值为 100

Swift conditional statementsSwift Conditional Statements