If - Else
Part of the Fundamentals section of Coddy's Swift journey — lesson 27 of 86.
Sometimes you need your program to do one thing when a condition is true and something different when it's false. The else clause provides an alternative path of execution.
let temperature = 15
if temperature > 25 {
print("It's warm outside")
} else {
print("It's cool outside")
}When the condition is false, the code inside the else block runs instead. This guarantees that exactly one of the two code blocks will always execute.
For situations with more than two possibilities, you can chain multiple conditions using else if:
let score = 75
if score >= 90 {
print("Excellent")
} else if score >= 70 {
print("Good")
} else if score >= 50 {
print("Pass")
} else {
print("Fail")
}Swift evaluates each condition from top to bottom and executes the first block where the condition is true. The final else acts as a catch-all for any remaining cases. This structure lets you handle multiple distinct scenarios in a clear, readable way.
Challenge
EasyWrite a function getAgeGroup that takes age and returns the corresponding age group category.
Use if, else if, and else to categorize the age into one of four groups.
Conditions:
- If age is less than
13, return"Child" - If age is at least
13but less than20, return"Teenager" - If age is at least
20but less than65, return"Adult" - If age is
65or older, return"Senior"
Parameters:
age(Int): The person's age
Returns: The age group category as a String
Cheat sheet
The else clause provides an alternative path when a condition is false:
if temperature > 25 {
print("It's warm outside")
} else {
print("It's cool outside")
}For multiple conditions, chain them using else if:
if score >= 90 {
print("Excellent")
} else if score >= 70 {
print("Good")
} else if score >= 50 {
print("Pass")
} else {
print("Fail")
}Swift evaluates conditions from top to bottom and executes the first block where the condition is true. The final else catches any remaining cases.
Try it yourself
func getAgeGroup(age: Int) -> String {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input