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 | let condition = true |
If you need to execute a different block of code when the condition is false, you can use the else
keyword:
1 | let condition = true |
In Swift, you have the option to wrap the condition in parentheses for readability:
1 | if (condition == true) { |
Alternatively, you can write the condition without explicitly comparing it to true
:
1 | if condition { |
You can also use the logical negation operator (!
) to check if a condition is false
:
1 | if !condition { |
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 | if condition = true { |
This is because the assignment operator does not return a value, but the if
statement requires a boolean expression as its condition.