Swift conditional statements


The conditional statement executes the program by setting one or more conditions. When the condition is true, the specified statement is executed, and when the condition is false, another specified statement is executed.

You can simply understand the execution process of conditional statements through the following figure:

1057.png

Swift provides the following types of conditional statements:

StatementDescription

if statement

if statement is expressed by a Boolean It consists of a formula and one or more execution statements.

if...else statement

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

if...else if...else statement

if can be followed by an optional else if...else statement, else if...else statement is often used for multiple conditional judgments.

Inline if statement

You can embed it in if or else if if or else if statement.

switch statement

The switch statement allows testing of a variable equal to multiple values.

? : Operator

We have already explained the conditional operator in the previous chapter? :, yes Used to replace the if...else statement. Its general form is as follows:

Exp1 ? Exp2 : Exp3;

where Exp1, Exp2 and Exp3 are expressions. Note the use and placement of colons.

? The value of the expression is determined by Exp1. If Exp1 is true, Exp2 is evaluated and the result is the value of the entire ? expression. If Exp1 is false, Exp3 is evaluated and the result is the value of the entire ? expression.