Swift Conditional Statements

Swift Conditional Statements are those which execute a block of code based on the result of a condition or boolean expression.

Swift supports following conditional statements.

We can use Logical Operators to form compound conditions. The following tutorials cover some of the scenarios where logical operators are used in conditions of Swift Conditional statements.

Examples

The following cover some of the conditional statements in Swift Programming.

If Statement

In the following example, we take an integer a = 10 and check if variable a is less than 20. Since the condition evaluates to true, the statements inside the if block execute.

main.swift

var a:Int = 10

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

Output

a is less than 20.
Program ended with exit code: 0

If-Else Statement

In the following example, we take an integer a = 30 and check if variable a is less than 20. As the expression evaluates to false, the statements inside the else block execute.

main.swift

var a:Int = 30

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

Output

a is not less than 20.
Program ended with exit code: 0

Switch Statement

In the following example, we have a simple expression with two variables. We have case blocks with values 4, 5, 6 and default. When the expression’s value matches any of the values, corresponding block is executed.

main.swift

var a=2
var b=3

switch a+b {
case 4 :
print("a+b is 4.")
print("a+b is four.")
case 5 :
print("a+b is 5.")
print("a+b is five.")
case 6 :
print("a+b is 6.")
print("a+b is six.")
default :
print("no value has been matched for a+b.")
}

Output

a+b is 5.
a+b is five.
Program ended with exit code: 0

Conclusion

In this Swift Tutorial, we have learned about conditional statements in Swift Programming.