31

Hello I am using Object Mapper with Alamofire in Swift and I am trying to map enum raw value to real Enum.

Here is my enum and also the code I am trying to use in function mapping. Can you please help me what to pass as argument to EnumTransform or how to modify the code? I know I can read the value as string and the use LevelType(rawValue: stringValue).

Thanks in advance.

enum LevelType : String {
    case NEW = "NEW"
    case UPDATE = "UPDATE"
}

func mapping(map: Map) {
    typeEnum <- (map[“type”], EnumTransformable(???) )
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Radim Halfar
  • 536
  • 2
  • 6
  • 15
  • It is not required to write case NEW = "NEW". "NEW" will be value by default(the same as name of case). enum LevelType : String { case NEW,UPDATE} will be the same – Bohdan Savych Mar 23 '17 at 14:48

2 Answers2

67

You don't have to pass an argument at all. All you have to do is to specify enum type as generic argument and ObjectMapper will take care for all enum initialization procedures.

 typeEnum <- (map["type"],EnumTransform<LevelType>())
Zell B.
  • 10,266
  • 3
  • 40
  • 49
  • 1
    I did the same as suggested here but i get the error saying -- Binary operator <- cannot be applied to string and (map , enumTranform()) – anamika41 Jul 21 '17 at 12:36
  • 2
    You need to declare enum type, var typeEnum: LevelType! – Thein Nov 21 '17 at 04:08
4

Just doing a straight map worked fine for me as long as my enum was declared to be of type String.

typeEnum <- map["type"]
Swindler
  • 802
  • 10
  • 9