I have an enum like
type
Color = enum
colRed,
colGreen,
colBlue
What is the best way to associate strings with the enum? Define a separate variable like this?:
let colorNames = toTable({colRed: "RED",
colGreen: "GREEN",
colBlue: "BLUE"})
Or is there a more elegant way to combine the enum definition with the string names?
I wouldn't use a table. An array fits better for this purpose
https://play.nim-lang.org/#ix=2lK1
for more elegant you could write a macro of course. But I think its an overkill for such a simple task.
type A = enum
a0 = "foo"
a1 = "bar"
or
const Names = [a0: "foo", a1: "bar"]
see also symbolName https://nim-lang.github.io/Nim/enumutils.html#symbolName%2CTEnums support strings as values directly. So you can have:
type
Color = enum
colRed = "RED"
colGreen = "GREEN"
colBlue = "BLUE"
and then stringifying an enum value using $ will simply print the string value. To convert a correct string into an enum value, there's parseEnum in strutils:
https://nim-lang.github.io/Nim/strutils.html#parseEnum%2Cstring
Alternatively, if you want to associate a type other than int or string, I'd use an array with enum values as indices (which works, because enums are ordinal values). For example:
var foo: array[Color, float]
foo[colRed] = 1.0
# etc.
Of course you can also define this as a constant array that is determined at compile time.
const foo = [colRed: 1.0, colGreen: 2.0, colBlue: 3.0]
Enums support strings as values directly
That's exactly what I was after! Thanks!
Note that $ is defined for enums and using pure enums you are an uppercase away from your goal:
type Color {. pure .} = enum
Red, Green, Blue
echo Color.Red
# Red