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")
}
// warmThe 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
BeginnerRead 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:cold10...19:mild20...29:warm30...39:hot40and 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 040...— one-sided range: 40 or greater- Order cases low-to-high; use
defaultfor the remaining catch-all
Try it yourself
let temp = Int(readLine()!)!
// TODO: switch on temp using ranges, print the matching label
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check