Swift - If-Else Statement

Introduction

An extension of the If statement is the If-Else statement.

The If-Else statement has the following syntax:

if  condition  {
    statement (s)
}  else {
       statement(s)
}

Any statements enclosed by the Else block are executed when the condition evaluates to false.

Here is an example:

var temperatureInCelsius = 25
if (temperatureInCelsius>30) {
    print("This is hot!")
} else {

    print("This is cooling!")
}

Here, the preceding code snippet checks the temperature (in Celsius) and outputs the statement "This is hot!" if it more than 30 degrees Celsius.

If it is less than or equal to 30 degrees Celsius, it outputs the statement "This is cooling!"

The Else block can also be another If-Else block, as the following example illustrates:

Demo

var temperatureInCelsius = 0
if temperatureInCelsius>30 {
     print("This is hot!")
} else if temperatureInCelsius>0 {

     print("This is cooling!")
} else {// w w w.  j ava2 s .co  m
      print("This is freezing!")
}

Result

Related Topic