Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nim: standard way to convert integer/string to enum

Tags:

enums

nim-lang

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"
like image 928
Andrey R Avatar asked Mar 23 '17 13:03

Andrey R


1 Answers

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)
like image 192
def- Avatar answered Sep 19 '22 11:09

def-