Long else if chains that compare the same variable over and over can be hard to read. Apex gives you the switch statement as a cleaner way to branch on the value of a single expression.
You write switch on followed by the value to test. Each when block lists one or more values to match. The when else block runs when nothing else matches:
Integer day = 3;
switch on day {
when 1 {
System.debug('Start of the week');
}
when 6, 7 {
System.debug('Weekend');
}
when else {
System.debug('A weekday');
}
}
Notice that one when can list several values separated by commas. Here 6 and 7 both map to the weekend branch.
Apex runs the first matching when block and then leaves the switch. Unlike some other languages, you do not write break after each branch, and there is no fall-through into the next one.
You can switch on an Integer, a Long, a String, or an sObject type. The values in each when must match the type of the expression:
String color = 'Green';
switch on color {
when 'Green' {
System.debug('Go');
}
when 'Red' {
System.debug('Stop');
}
when else {
System.debug('Unknown');
}
}
When you are choosing between several fixed values of one variable, a switch is easier to read than a stack of else if statements. Always include a when else branch so that unexpected values are handled cleanly.