if else-if else Conditional Statements in Swift

In Swift, the if else statement is used for conditional branching in which a block of code is executed if a certain condition is true, otherwise, another block of code is executed.

First we declare a variable named weatherIsGood with the boolean value true. Then follows the  syntax of an if-else-statement. In this code example, the condition is a boolean expression that is evaluated to either true or false (true in our case)

var weatherIsGood = true

if weatherIsGood {
    print("Let's go for a walk!")
} else {
    print("Better stay inside!")

Alternatively, you can also add else-if clause to your control flow in order to implement multiple conditions check. The syntax would look like this:

var weather = "sunny"

if weather == "sunny" {
    print("Don't forget your sunglasses!")
} else if weather == "rainy" {
    print("Take your umbrella!")
} else {
    print("Check your weather app first!")

Overall, the if else statement is a way to control the flow of the program based on certain conditions, and it is a fundamental concept in programming.

Leave a Reply

Your email address will not be published. Required fields are marked *