Switch in Nim

Switch Statements in Nim

Switch statements express conditionals across many branches. Here is an example of how you can use switch statements in Nim.

Here’s a basic case statement in Nim.

import times

proc main() =
  let i = 2
  echo "Write ", i, " as "
  case i:
  of 1:
    echo "one"
  of 2:
    echo "two"
  of 3:
    echo "three"

  # You can use commas to separate multiple expressions in the same `of` statement.
  case now().weekday:
  of Sat, Sun:
    echo "It's the weekend"
  else:
    echo "It's a weekday"

  # `case` without an expression is an alternate way to express if/else logic.
  let t = now()
  case true:
  of t.hour < 12:
    echo "It's before noon"
  else:
    echo "It's after noon"

  # A type `case` compares types instead of values.
  proc whatAmI(i: ref object) =
    case i.type:
    of bool:
      echo "I'm a bool"
    of int:
      echo "I'm an int"
    else:
      echo "Don't know type ", i.type

  whatAmI ref false
  whatAmI ref 1
  whatAmI ref "hey"

main()

To run the program, save the code in a file (e.g., switch_example.nim) and use nim to execute it.

$ nim compile --run switch_example.nim
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string

Now that we can run and build basic Nim programs, let’s learn more about the language.