Menu
Coddy logo textTech

Ranges in Switch

Part of the Logic & Flow section of Coddy's Swift journey — lesson 10 of 56.

You used switch with ranges in fundamentals. The same trick scales to real classification problems where each case covers a band of values.

let temp = 22
switch temp {
case ..<0:        print("freezing")
case 0..<10:      print("cold")
case 10..<20:     print("mild")
case 20..<30:     print("warm")
default:           print("hot")
}
// warm

The first case ..<0 uses the one-sided range form: "any value strictly less than 0". You can use 0... to mean "0 or greater" too.

Cases are checked top-down and the first match wins, so order them from low to high (or use default for the catch-all).

challenge icon

Challenge

Beginner

Read a single integer from input: a temperature in Celsius. Print one of these labels using a single switch with range cases:

  • Below 0 (negatives): freezing
  • 0...9: cold
  • 10...19: mild
  • 20...29: warm
  • 30...39: hot
  • 40 and above: scorching

For input 22, the output is warm.

Cheat sheet

Use switch with range cases to classify values. Cases are checked top-down; first match wins.

let temp = 22
switch temp {
case ..<0:        print("freezing")   // one-sided: anything below 0
case 0..<10:      print("cold")
case 10..<20:     print("mild")
case 20..<30:     print("warm")
default:          print("hot")        // catch-all
}
// warm
  • ..<0 — one-sided range: any value strictly less than 0
  • 40... — one-sided range: 40 or greater
  • Order cases low-to-high; use default for the remaining catch-all

Try it yourself

let temp = Int(readLine()!)!

// TODO: switch on temp using ranges, print the matching label
quiz iconTest yourself

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

All lessons in Logic & Flow