3

Say I have an enum like this:

enum Direction {
  case Left
  case Right
}

Is there a way to derive a string description of the enum automatically without defining it myself? Something like this:

let direction: Direction = .Left
let description: String = direction.description // should be "Left"

I tried reflect( direction) and the properties on MirrorType but that didn't work.

lassej
  • 6,256
  • 6
  • 26
  • 34

2 Answers2

2

Not currently. You'll need to implement a description function manually for this. Swift has very limited reflection.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
2

I think the closest you can do is either implement description yourself or make the enum a string:

enum Direction: String {
  case Left = "Left"
  case Right = "Right"
}

You can then get the value via direction.rawValue. Obviously, not as great as what you are looking for though and it requires duplicating the enum value, which is dumb.

You can then use the raw value to implement the description if you want (allowing you to use direction.description:

var description: String {
    return self.rawValue
}
Firo
  • 15,448
  • 3
  • 54
  • 74