The question is Nim language specific. I am looking for a standard to way to convert integer/string into enum in a type safe way. Converting from enum to integer/string is easy using ord() and $(), but i can't find an easily way to make opposite transformation.
Suppose I have the following type declaration
ProductGroup {.pure.} = enum
Food = (3, "Food and drinks"),
kitchen = (9, "Kitchen appliance and cutlery"),
Bedroom = (15, "Pillows, Beddings and stuff"),
Bathroom = (17, "Shower gels and shampoo")
I am looking for a standard way to do:
const
product1 : seq[ProductGroup] = xxSomethingxx(@[3, 3, 17, 9, 15])
product2 : seq[ProductGroup] = zzSomethingzz(@["Kitchen appliance and cutlery", "Kitchen appliance and cutlery", "Shower gels and shampoo"])
product3 : seq[ProductGroup] = xxSomethingxx(@[2]) ## compilation error "2 does not convert into ProductGroup"
Type conversion from int to enum, strutils.parseEnum from string to enum:
import strutils, sequtils
type ProductGroup {.pure.} = enum
Food = (3, "Food and drinks"),
kitchen = (9, "Kitchen appliance and cutlery"),
Bedroom = (15, "Pillows, Beddings and stuff"),
Bathroom = (17, "Shower gels and shampoo")
const
product1 = [3, 3, 17, 9, 15].mapIt(ProductGroup(it))
product2 = ["Kitchen appliance and cutlery", "Kitchen appliance and cutlery", "Shower gels and shampoo"].mapIt(parseEnum[ProductGroup](it))
product3 = ProductGroup(2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With