Conditional Statements in Swift- If statement

Swift provides two ways to add conditional branches to your code, known as the if statement and the switch statement. Typically, you use the if statement to evaluate simple conditions with only a few possible outcomes. In its simplest form, the if statement has a single if condition. It executes a set of statements only if that condition is true. The syntax is as follow.

Consider the following example:

The preceding example checks whether the temperature is less than or equal to 32 degrees. If it is, a message is printed. Otherwise, no message is printed, and code execution continues after the if statement’s closing brace.

The if statement can provide an alternative set of statements, known as an else clause, for when the ifcondition is false. These statements are indicated by the else keyword:

One of these two branches is always executed. Because the temperature has increased to 40 degrees Fahrenheit, it is no longer cold enough to advise wearing a scarf, and so the else branch is triggered instead.

You can chain multiple if statements together, to consider additional clauses by using else if:

 

Next we will learn about Switch statements.