If-else statements are fundamental control flow structures in Swift programming. They allow developers to execute different code blocks based on specific conditions.
The basic syntax of an if-else statement in Swift is as follows:
if condition {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
An if statement can be used alone to execute code only when a condition is true:
let temperature = 25
if temperature > 30 {
print("It's hot outside!")
}
When you need to handle two mutually exclusive conditions, use an if-else statement:
let score = 85
if score >= 70 {
print("You passed!")
} else {
print("You failed.")
}
For more complex decision-making, use else if to check multiple conditions:
let grade = 88
if grade >= 90 {
print("A")
} else if grade >= 80 {
print("B")
} else if grade >= 70 {
print("C")
} else {
print("F")
}
You can nest if statements within each other for more complex logic:
let isRaining = true
let hasUmbrella = false
if isRaining {
if hasUmbrella {
print("Take your umbrella")
} else {
print("Wear a raincoat")
}
} else {
print("Enjoy the weather!")
}
To further enhance your understanding of control flow in Swift, explore these related topics:
Mastering if-else statements is crucial for writing efficient and readable Swift code. Practice using them in various scenarios to become proficient in controlling your program's flow.