Swift If

Swift if statement is used to implement a conditional logic in the program.

Syntax for Swift if

Swift if statements has two parts. The first one is boolean expression. The second part is set of statements.

Following is the syntax for Swift if statement.

if boolean_expression {
   /* set of 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 if block are not executed.

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

ADVERTISEMENT

Example 1 – Swift if

In this 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.

main.swift

var a:Int = 10

/* boolean expression to check if a is less than 20 */
if a < 20 {
   /* set of statements */
   print("a is less than 20")
}

print("rest of the statements")

Output

$swift main.swift
a is less than 20
rest of the statements

Example 2 – Swift if

In this 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 continue with the rest of the statements after swift if statement.

main.swift

var a:Int = 10

/* boolean expression to check if a is less than 20 */
if a < 20 {
   /* set of statements */
   print("a is less than 20")
}

print("rest of the statements")

Output

$swift main.swift
rest of the statements

Conclusion

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