/

Swift Conditionals: Using the `if` Statement

Swift Conditionals: Using the if Statement

Tags: Swift, Conditionals, if statement

In Swift, the if statement is a widely used conditional construct. It allows you to check a condition and execute a block of code if the condition is true. Here’s an example:

1
2
3
4
let condition = true
if condition == true {
// code executed if the condition is true
}

If you need to execute a different block of code when the condition is false, you can use the else keyword:

1
2
3
4
5
6
let condition = true
if condition == true {
// code executed if the condition is true
} else {
// code executed if the condition is false
}

In Swift, you have the option to wrap the condition in parentheses for readability:

1
2
3
if (condition == true) {
// ...
}

Alternatively, you can write the condition without explicitly comparing it to true:

1
2
3
if condition {
// runs if `condition` is `true`
}

You can also use the logical negation operator (!) to check if a condition is false:

1
2
3
if !condition {
// runs if `condition` is `false`
}

A notable feature of Swift is that it prevents common bugs caused by accidentally using the assignment operator instead of the equality operator. For example, the following code will not compile:

1
2
3
if condition = true {
// The program does not compile
}

This is because the assignment operator does not return a value, but the if statement requires a boolean expression as its condition.