Swift Conditional Statements

Conditional Statements in Swift:

In Swift, Conditional Statements are those statements that execute a block of code based on the result of a condition or boolean expression.

Types of Conditional Statements in Swift:

There are mainly 7 types of Conditional Statements in Swift programming.

1. if Statement:

In Swift, an if statement executes a code block when its condition evaluates to true. If the condition is false, the code block does not execute.

2. if-else Statement:

In Swift, an if-else statement is used to implement conditional logic in the program for both true and false conditions. If-else statements have three parts. The first one is a boolean expression. The second part is a set of statements in an if-block. The third part is a set of statements in the else block.

if boolean_expression
/* if block statements */
} else
/* else block statements */

The boolean expression is evaluated in runtime. If the boolean expression evaluates to true, then the set of statements in the if block is executed. If the boolean expression evaluates to false, the set of statements in the else block is executed.

3. else-if Statement:

An else-if statement provides additional conditions to check for within a standard if-else statement.

4. nested if Statement:

When you use an if statement inside of an if statement, that is called a nested if statement.

5. Comparison Operators:

Comparison operators are used to compare the values of two operands and return a Boolean result.

< less than > greater than
<= less than or equal to >= greater than or equal to
== equal to
!= not equal to

6. Ternary Conditional Operator:

It evaluates a single condition and if true, executes the code before the [html]:[/html]. If the condition is false, the code following the [html]:[/html] is executed. The ternary conditional operator, denoted by [html]?[/html].

7. Switch Statement:

Switch statement is a type of conditional used to check the value of an expression against multiple cases. A case executes when it matches the value of the expression. When there are no matches between the case statements and the expression, the default statement executes.