LessonsBeginner: First stepsLesson 10

Many choices with switch

Pick one of many paths with switch, case, break and default, and when to prefer it to a chain of ifs.

  • Beginner
  • Lesson 10 of 83
  • About 7 minutes
  • 5 examples

One value, many cases

When you compare one value against many possibilities, switch is tidier than a long chain of else if. Each case gives a value; xTalk runs the lines of the first one that matches, until a break. default runs when nothing matched.

ExampleRun it in the playground
put "Save" into tChoice
switch tChoice
   case "Open"
      put "Opening a file"
      break
   case "Save"
      put "Saving your work"
      break
   default
      put "Not a menu item:" && tChoice
end switch
Output
Saving your work

Several values, one answer

Cases with no lines between them share the lines that follow. Matching text ignores capitals, as every text comparison does.

ExampleRun it in the playground
put "SUN" into tDay
switch tDay
   case "Sat"
   case "Sun"
      put "Weekend"
      break
   default
      put "Weekday"
end switch
Output
Weekend

Do not forget break

Without break, xTalk carries on into the next case's lines, whether it matches or not. Occasionally that is what you want; usually it is a bug.

ExampleRun it in the playground
put 2 into tLevel
switch tLevel
   case 1
      put "Easy"
   case 2
      put "Medium" -- no break here...
   case 3
      put "Hard"   -- ...so this runs too
      break
   default
      put "Unknown level"
end switch
Output
Medium
Hard

Cases that are conditions

A switch with nothing after it takes a condition in each case, and runs the first that is true. It reads well for ranges.

ExampleRun it in the playground
put 37 into tCelsius
switch
   case tCelsius < 0
      put "Freezing"
      break
   case tCelsius < 20
      put "Mild"
      break
   case tCelsius < 35
      put "Warm"
      break
   default
      put "Hot"
end switch
Output
Hot

Try it yourself

Write a switch that turns a month's number (1 to 12) into its season in the northern hemisphere: 12, 1 and 2 are winter, 3 to 5 spring, 6 to 8 summer, and 9 to 11 autumn. Try it with month 4.

Show a solution
ExampleRun it in the playground
put 4 into tMonth
switch tMonth
   case 12
   case 1
   case 2
      put "Winter"
      break
   case 3
   case 4
   case 5
      put "Spring"
      break
   case 6
   case 7
   case 8
      put "Summer"
      break
   default
      put "Autumn"
end switch
Output
Spring

Words in this lesson

Each one finds every lesson that uses it. The Dictionary has the whole story of each, with its syntax and more examples.