Understanding Swift Else if Statement
Introduction
In Swift, an if statement can be extended with optional
else if and else clauses to handle
multiple conditions sequentially. This structure allows for precise
decision-making based on different conditions.
The if...else if...else construct forms a decision tree
where each condition is checked in order. The first condition that
evaluates to true will execute its corresponding block
of code. If none of the conditions are met, the
else block executes.
This structure is also commonly referred to as the if-else ladder.
Key Points to Remember
-
An
ifstatement can have zero or oneelseclause, which must appear after allelse ifclauses. -
An
ifstatement can have zero to manyelse ifclauses, which must precede theelseclause. -
Once an
else ifcondition is met, subsequentelse ifandelseblocks are ignored.
Syntax
if condition1 {
// Executes when condition1 is true
} else if condition2 {
// Executes when condition2 is true
} else if condition3 {
// Executes when condition3 is true
} else {
// Executes when none of the above conditions are met
}
Example 1: Checking an Integer Value
Let's demonstrate how to use an
if...else if...else statement in Swift.
import Foundation
var value: Int = 42
if value < 10 {
print("Value is less than 10")
} else if value < 50 {
print("Value is between 10 and 49")
} else {
print("Value is 50 or greater")
}
print("Final value: \(value)")
Output
Final value: 42
Example 2: Determining the Type of a Number
import Foundation
let number = -5
if number > 0 {
print("Positive number")
} else if number < 0 {
print("Negative number")
} else {
print("Number is zero")
}
Output
Example 3: Categorizing an Age Group
import Foundation
let age = 25
if age < 13 {
print("Child")
} else if age < 20 {
print("Teenager")
} else if age < 60 {
print("Adult")
} else {
print("Senior")
}