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:
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:
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:
if (condition == true) {
// ...
}
Alternatively, you can write the condition without explicitly comparing it to true
:
if condition {
// runs if `condition` is `true`
}
You can also use the logical negation operator (!
) to check if a condition is false
:
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:
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.