• Reference Guide

switch Statement

VALUE-LIST is a list of one or more values separated by commas. The values must be specified by constant expressions. The values specified in the list must be of the same type as the expr parameter is. This limitation can be circumvented by specifying the expr parameter of the Union type. This can be done using the typecast operator. In that case, however, no type conversions are performed during execution (i.e., for instance, [Byte]0 and [Int]0 are two distinct cases). Each value can be used at most once in value lists within entire switch statement.
The switch statement serves to branch execution based on the value specified by the expr parameter. The statement body consists of a sequence of branches, the each of which consists of a value list and an associated block. A block is executed when the value returned by the expr parameter is contained in its associated value list.
A value list is labeled with the case keyword followed with one or more comma-separated values. Optionally, the list can be split up into more parts, each beginning with a separate case keyword. As long as the case clauses follow immediately one after another, they form a single value list followed by a single block. (The possibility of splitting the value list is motivated by the custom practice in the C language and similar.)
case 1, 2, 3:
case 1:
case 2:
case 3:
are the same.
Besides of that, an else (or default:) branch can be present, which is evaluated, if the value has not been found in any case branch. The else and default: keywords are interchangeable, reflecting different custom practices in different programming languages. However, in a single switch statement can be used at most one of them.
The result of the switch statement is the value returned by the evaluated block. If no block for the value was found, the result is the initial value of the type returned by other branches.
The block expressions are blocks in the sense that the scope of variables defined within them is limited to the block.
Caution: On contrary to the C language and similar, only one block is evaluated for a given value. Thus, the evaluation never continues to the following blocks. Therefore, there is no need to terminate block with the break statement (actually, it is not allowed, at all).
var String str = switch(x)
case 1: "one"
case 2: "two"
case 3: "three"
else "many"

See Also