Welcome to the Swift if-else statements tutorial! In this lesson, we'll dive deep into understanding the Swift conditional statements and how they help make your code more dynamic and flexible. Let's get started! 📝
If-else statements are control structures used in Swift programming to make decisions based on conditions. They allow your code to evaluate different branches based on certain conditions, making your programs more responsive and adaptive to user input or data.
if condition {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}Let's break this down:
if condition: Swift evaluates the condition. If the condition is true, the code inside the if block will be executed.else: If the condition is false, the code inside the else block will be executed.let age = 18
if age >= 18 {
print("You are eligible to vote!")
} else {
print("You are not eligible to vote yet.")
}In this example, the variable age is assigned the value 18. The if condition checks if age is greater than or equal to 18. Since it is, the code inside the if block is executed, and "You are eligible to vote!" is printed. ✅
You can also use if-else to compare multiple conditions.
let score = 85
if score >= 90 {
print("You got an A grade!")
} else if score >= 80 {
print("You got a B grade!")
} else if score >= 70 {
print("You got a C grade!")
} else {
print("You need to study harder.")
}In this example, we compare the score variable against multiple conditions. Starting from the first if condition, if the condition is true, the corresponding block will be executed. If the condition is false, Swift moves on to the next else if condition. If none of the conditions are true, the code inside the final else block will be executed. ✅
You can also nest if-else statements inside other if-else statements to create complex decision-making structures.
let temperature = 28
if temperature > 30 {
print("It's very hot outside!")
} else if temperature > 20 {
print("It's quite warm outside.")
} else if temperature > 10 {
print("It's a bit chilly outside.")
} else {
print("It's freezing outside!")
}In this example, the temperature variable is compared against multiple conditions. Depending on the temperature, a different message will be printed. ✅
:::quiz Question: Which of the following options correctly uses an if-else statement to print "You are eligible to vote" if the user's age is 18 or older?
A:
let age = 18
if age > 18 then {
print("You are eligible to vote.")
}B:
let age = 18
if age >= 18 {
print("You are eligible to vote.")
} else {
print("You are not eligible to vote.")
}C:
let age = 18
if age is 18 {
print("You are eligible to vote.")
}Correct: B
Explanation: Option B correctly uses the if-else statement to check if the user's age is 18 or older and print the appropriate message. Option A has an incorrect syntax, and Option C uses the wrong operator (is should be == for comparing integer literals in Swift). ✅