Swift conditional statement

A conditional statement executes a program by setting one or more conditions, executing the specified statement when the condition is true, and executing a separately specified statement when the condition is false.

The following diagram provides a brief understanding of how conditional statements are executed:

Swift conditional statement

Swift provides several types of conditional statements:

Statement Describe

The if statement

An if statement consists of a Boolean expression and one or more execution statements.

if... Else statement

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

if... e lse if... Else statement

If can be then there can be optional else if... e lse statement, else if... Else statements are often used for multiple conditional judgments.

The if statement is embedded

You can insert an if or else if statement in an if or else if.

Switch statement

The switch statement allows you to test when a variable is equal to more than one value.

? : Operator

We've covered the conditional operator ? , which can be used instead of if... E lse statement. Its general form is as follows:

Exp1 ? Exp2 : Exp3;

Exp1, Exp2, and Exp3 are expressions. Note the use and location of the colon.

? T he value of the expression is determined by Exp1. I f Exp1 is true, the value of Exp2 is calculated and the result is the entire ? T he value of the expression. I f Exp1 is false, the value of Exp3 is calculated, and the result is the entire ? The value of the expression.