SWIFT conditional statement
A conditional statement executes a program by setting one or more conditions, executing the specified statement if the condition is true, and executing another specified statement if the condition is false.
The execution of a conditional statement can be easily understood by following the figure below:
Swift provides the following types of conditional statements:
statements | describe |
---|---|
If statement | If statementConsisting of a Boolean expression and one or more execution statements. |
if… Else statements | If statementThere can be optional laterElse statements.Else statementsExecutes when the Boolean expression is false. |
if… else if… Else statements | ifThere can be optional laterelse if… elseStatements,else if… elseStatements are often used to determine multiple conditions. |
Embedded if statement | You can be inif 或 else ifembeddedif 或 else ifStatements. |
A switch statement | The switch statement allows you to test when a variable equals more than one value. |
? : operator
We’ve covered conditional operators in the previous section. Okay? Can be used instead of if… The else statement. Its general form is as follows:
Exp1 ? Exp2 : Exp3;
Where, Exp1, Exp2, and Exp3 are expressions. Note the use and placement of the colon.
? The value of the expression is determined by Exp1. If Exp1 is true, then Exp2 is evaluated, and the result is the whole thing, right? The value of the expression. If Exp1 is false, then Exp3 is evaluated, and the result is the whole thing, right? The value of the expression.