Conditional statements (if, else, else if) - Swift Tutorial
In Swift, you can use conditional statements to control the flow of your code based on certain conditions. The three main conditional statements are if
, else
, and else if
.
The if
statement: It allows you to execute a block of code only if a certain condition is true. The basic syntax is as follows:
if condition {
// Code to execute if the condition is true
}
Here’s an example that checks if a number is positive:
let number = 10
if number > 0 {
print("The number is positive.")
}
The else
statement: It is used along with the if
statement to specify an alternative block of code to execute if the condition is false. Here's an example:
let number = -5
if number > 0 {
print("The number is positive.")
} else {
print("The number is not positive.")
}
In this case, since the condition number > 0
is false, the code inside the else
block will be executed.
The else if
statement: It allows you to specify additional conditions to check if the previous condition is false. You can chain multiple else if
statements as needed. Here's an example:
let number = 0
if number > 0 {
print("The number is positive.")
} else if number < 0 {
print("The number is negative.")
} else {
print("The number is zero.")
}
In this example, since none of the conditions number > 0
and number < 0
are true, the code inside the else
block will be executed.
You can also combine multiple conditions using logical operators like &&
(AND) and ||
(OR) to create more complex conditions.
It’s worth noting that Swift also provides other conditional statements, such as the switch
statement, which can be used for more extensive branching based on different cases.
If you’re interested in learning more about Swift, I recommend checking out my articles on Medium. You can access them through the template I created on Notion, which provides a structured learning process and easy navigation to different topics. Happy learning, and best of luck on your Swift programming journey!