Switch case is a common control flow statement provided by every language.
Nim Provides case statements. These are similar to if else conditional expressions
Nim case statement example
case expression evaluates to a value, and the value is matched with of statement and executes statements inside it.
case conditional_expression: of "value": // statements; of "value": // statements; of "value": // statements; else: //default case statements;
conditional_expression is evaluated to ordinal value data types such as strings, bool, chars, and integers, value is compared with
of value, and matched
if statements are executed.
conditional_expression can be variable.
if no matching is found, the default else statement is executed.
let number = 10 case number: of 1: echo "value is 1" of 2: echo "value is 2" of 2: echo "value is 3" else: echo "value is not 1 or 2 or 3"
value is not 1 or 2 or 3
of the statement contains a range of values using two dots operator
let number = 100 case number: of 1..9: echo "single digit" of 10-99: echo "double digit" of 100-999: echo "triple digit" else: echo " 4 or more digits"
of statement can also contain multiple values separated by a comma.
let number = 'two' case number: of 'one", 'two': echo "one or two" else: echo " Not one or two"
one or two