Swift if-else Statement
The if-else statement is a fundamental control structure in Swift used for decision-making. It allows for conditional execution of code based on whether a condition is true or false.
Syntax
The basic syntax of the if-else statement in Swift is as follows:
if condition {
// code to execute if the condition is true
}
else {
// code to execute if the condition is false
}
Example
Here's an example of how the if-else statement is used in Swift:
let num = 10
if num % 2 == 0 {
print("\(num) is even")
}
else {
print("\(num) is odd")
}
Output
The output of the above code would be:
10 is even
Explanation
In the above code, we first declare a variable num
and assign it the value 10. We then use an if-else statement to check if num
is even or odd. The condition we check is whether the remainder of num
divided by 2 is equal to 0. If the condition is true, we print that num
is even. If the condition is false, we print that num
is odd.
Use
The if-else statement in Swift can be used in a variety of scenarios, such as:
- Checking if a user is logged in
- Validating user input
- Checking if a number is positive or negative
- Handling errors or exceptions
Important Points
- The if-else statement is a fundamental control structure in Swift used for decision-making.
- The condition within the if statement must either be true or false.
- The code to execute if the condition is true is placed within the curly braces immediately following the if statement.
- The code to execute if the condition is false is placed within the curly braces following the else statement.
- The if-else statement can be used in a variety of scenarios, such as validating user input or handling errors.
Summary
The if-else statement is an important control structure in Swift that allows for conditional execution of code based on whether a condition is true or false. It can be used in a variety of scenarios and is fundamental to building complex applications.