3

Now I need a convenient way to get the name of enumeration itself ? Here is an example.

enum SimpleEnum {
    case firstCase
    case secondCase
    case thirdCase
}
let simpleEnum: SimpleEnum = .firstCase
print("\(simpleEnum)") // return the "firstCase", but I want "SimpleEnum"

I know the following code would work.

enum SimpleEnum: CustomStringConvertible {
    case firstCase
    case secondCase
    case thirdCase

    var description: String { return "SimpleEnum" }
}
let simpleEnum: SimpleEnum = .firstCase
print("\(simpleEnum)") // Ok, it return "SimpleEnum"

However, I just want an universal way instead of typing "SimpleEnum" for each enum.

Hamish
  • 78,605
  • 19
  • 187
  • 280
Vitreous-Flower
  • 257
  • 3
  • 18

1 Answers1

12

You can get the type object from an enum case by calling type(of:). You can then convert that to a string by calling String.init(describing:):

let simpleEnum: SimpleEnum = .firstCase
let enumName = String(describing: type(of: simpleEnum))

If you want to get the type name from a type instead, you can do this:

let enumName = String(describing: SimpleEnum.self)
Sweeper
  • 213,210
  • 22
  • 193
  • 313