Swift if...else statement

Swift 条件语句Swift conditional statements

aif statementcan be followed by an optionalelse statement, the else statement executes when the boolean expression is false.

Syntax

In the Swift languageif...elsethe syntax of the statement:

if boolean_expression {
   /* 如果布尔表达式为真将执行的语句 */
} else {
   /* 如果布尔表达式为假将执行的语句 */
}

If the boolean expression istrue, then executeifthe code inside the block. If the boolean expression isfalse, then executeelsethe code inside the block.

Flowchart

C 中的 if...else 语句

Example

import Cocoa

var varA:Int = 100;

/* 检测布尔条件 */
if varA < 20 {
   /* 如果条件为 true 执行以下语句 */
   print("varA 小于 20");
} else {
   /* 如果条件为 false 执行以下语句 */
   print("varA 大于 20");
}
print("varA 变量的值为 \(varA)");

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

varA 大于 20
varA 变量的值为 100

Swift 条件语句Swift conditional statements

Other extensions