Swift If-Else

Welcome to Swift Tutorial. In this tutorial, we will learn about Swift if-else conditional statement with examples.

Swift if-else statement is used to implement a conditional logic in the program for both true and false scenarios.

Syntax – Swift if-else

Swift if-else statements has three parts. The first one is boolean expression. The second part is set of statements in if-block. The third part is set of statements in else-block.

Following is the syntax for Swift if statement.

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

// rest of the statements

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

The program execution continues with rest of the statements after the if-else conditional statement.

Example 1 – Swift if-else

In the following example, we will consider an integer variable a = 10 and check if variable a is less than 20. As the expression should evaluate to true, the statements inside the if block should execute and the statements inside else block should not execute.

main.swift

var a:Int = 10

/* boolean expression to check if a is less than 20 */
if a < 20 {
    /* if block statements */
    print("a is less than 10")
} else {
    /* else block statements */
    print("a is not less than 10")
}

print("rest of the statements")

Output

$swift if_else_example.swift
a is less than 10
rest of the statements

Example 2 – Swift if-else

In the following example, we will consider an integer variable a = 20 and check if variable a is less than 10. As the expression should evaluate to false, the statements inside the if block should not execute, but statements inside else block should execute.

main.swift

var a:Int = 20

/* boolean expression to check if a is less than 10 */
if a < 10 {
    /* if block statements */
    print("a is less than 10")
} else {
    /* else block statements */
    print("a is not less than 10")
}

print("rest of the statements")

Output

$swift if_else_example.swift
a is not less than 10
rest of the statements

Conclusion

In this Swift Tutorial, we have learned Swift if-else conditional statement with the help of syntax and examples.