Product SiteDocumentation Site

11.3.8.4. "Switch Execution to This Path"

A "switch" structure can be most easily understood by comparison to a switch in a railway line. As a train approaches a railway switch, an operator inspects the train, and decides whether it should be going to the passenger station, the freight station, or the garage for storage. A "switch" structure - like a railways switch, can only act on one Object at a time, but the Object can be a Collection, allowing you to compare multiple things at once. Each case is tested with the boolean equality operator before being executed.
Here is the syntax of a "switch" statement:
case( compareThis,
   toThis1, { doThis; },
   toThis2, { doThis; },
   toThis3, { doThis; }
);
You can include any number of cases. Notice that there is no comma after the last case, and that I've put the concluding ");" on a separate line with the same indentation as the word "case", so that it's easy to see.
The following example shows a simple switch.
(
   var grade  = 11.rand + 1; // pseudo-randomly chooses 0 to 11, then adds 1 to give 1 to 12

   grade =
   switch( grade,
      1, { "D-" },
      2, { "D" },
      3, { "D+" },
      4, { "C-" },
      5, { "C" },
      6, { "C+" },
      7, { "B-" },
      8, { "B" },
      9, { "B+" },
      10, { "A-" },
      11, { "A" },
      12, { "A+" }
   );

   ("Your grade is" + grade).postln;
   nil;
)
The code picks a pseudo-random number between 1 and 12, then uses a "switch" structure to convert that number into a letter-grade, assigning it to the same grade variable. Then, it adds the "Your grade is" string to the value of grade (with a space between), and prints that result.
This example avoids the complex nested "if" structure from above.
(
   var testA = [1,2,3].choose; // pseudo-randomly chooses one of the elements in the List
   var testB = [1,2,3].choose;

   switch( [testA,testB],
      [1,1], { "It's one and one!".postln; },
      [1,2], { "It's one and two!".postln; },
      [1,3], { "It's one and three!".postln; },
      [2,1], { "It's two and one!".postln; },
      [2,2], { "It's two and two!".postln; },
      [2,3], { "It's two and thre!".postln; },
      [3,1], { "It's three and one!".postln; },
      [3,2], { "It's three and two!".postln; },
      [3,3], { "It's three and three!".postln; }
   );

   nil;
)
This is an elegant way to inspect two otherwise-separate variables. Remember that the first argument to "switch" (in this case, it's [testA,tesB]) is compared to the first argument of possibe result with the equality operator: ==
When evaluating which switch to use, the SuperCollider interpreter will always apply the last one that evaluates to true.
(
   switch( 5,
      5, { "one".postln; },
      5, { "two".postln; },
      5, { "three".postln; }
   );

   nil;
)
All of these cases are true, but this will always result in "three" being printed.