Menu
Coddy logo textTech

Switch With Ranges

Part of the Fundamentals section of Coddy's Swift journey. Lesson 30 of 86.

Switch statements become even more powerful when you use ranges instead of individual values. This is perfect for categorizing numbers into groups, like converting a score into a grade.

let score = 85

switch score {
case 90...100:
    print("A")
case 80..<90:
    print("B")
case 70..<80:
    print("C")
case 60..<70:
    print("D")
default:
    print("F")
}

The ... operator creates a closed range that includes both endpoints, so 90...100 matches 90, 91, all the way through 100. The ..< operator creates a half-open range that excludes the upper bound — 80..<90 matches 80 through 89.

Swift checks each case in order and executes the first matching one. Since our score is 85, it falls within 80..<90, so "B" gets printed. This approach is much cleaner than writing multiple else if conditions with comparison operators.

challenge icon

Challenge

Easy
Write a function getAgeCategory that takes age and returns the life stage category based on age ranges.

Use a switch statement with ranges to categorize the age into one of five life stages.

Conditions:

  • 0...2 - return "Infant"
  • 3...12 - return "Child"
  • 13...19 - return "Teenager"
  • 20...64 - return "Adult"
  • 65...120 - return "Senior"
  • Any other value - return "Invalid age"

Parameters:

  • age (Int): The person's age

Returns: The life stage category as a String

Try it yourself

func getAgeCategory(age: Int) -> String {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Swift playground