Swift Conditional Statements
Conditional statements execute programs based on one or more set conditions. When a condition is true, the specified statement(s) are executed; when the condition is false, other specified statement(s) are executed.
The execution flow of conditional statements can be simply understood from the following diagram:
Swift provides the following types of conditional statements:
| Statement | Description |
|---|---|
| if statementConsists of a boolean expression and one or more executable statements. | |
| if statementcan be followed by an optionalelse statement, else statementExecuted when the boolean expression is false. | |
| ifcan be followed by an optionalelse if...elsestatement,else if...elseThe statement is often used for multiple condition judgments. | |
| You caniforelse ifnestiforelse ifstatements. | |
| The switch statement allows testing a variable against multiple values. |
? : Operator
We have already explained in previous chaptersthe conditional operator ? :, which can be used to replaceif...elsestatements. Its general form is as follows:
Exp1 ? Exp2 : Exp3;
Here, Exp1, Exp2, and Exp3 are expressions. Note the usage and position of the colon.
The value of the ? expression is determined by Exp1. If Exp1 is true, the value of Exp2 is evaluated, and the result is the value of the entire ? expression. If Exp1 is false, the value of Exp3 is evaluated, and the result is the value of the entire ? expression.
Other Extensions