Swift Conditional Statements
Conditional statements execute a program based on one or more conditions. They specify statements to be executed when the condition is true and different statements when the condition is false.
The execution process of conditional statements can be understood with the help of the following diagram:
Swift provides several types of conditional statements:
Statement | Description |
---|---|
if statement | An if statement consists of a Boolean expression followed by one or more statements. |
if...else statement | An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. |
if...else if...else statement | An if statement can be followed by an optional else if...else statement, commonly used for multiple condition checks. |
Nested if statements | You can nest if or else if statements within another if or else if statement. |
switch statement | A switch statement allows testing a variable against multiple values. |
? : Operator
We have discussed the conditional operator ? : in previous chapters, which can be used to replace if...else statements. Its general form is as follows:
Exp1 ? Exp2 : Exp3;
Here, Exp1, Exp2, and Exp3 are expressions. Note the use and position of the colon.
The value of the ? expression is determined by Exp1. If Exp1 is true, the value of Exp2 is computed and becomes the value of the entire ? expression. If Exp1 is false, the value of Exp3 is computed and becomes the value of the entire ? expression.