1

To get a string description of the enum value, I can usually just print it out as shown in this answer.

enum CustomEnum {
    case normal
    case special
}
let customEnum = CustomEnum.normal
print("Custom enum is: \(customEnum)")

Result:

But, this doesn't work for system enums, for example UIView.ContentMode. It just prints out the name of the enum itself.

let imageView = UIImageView()
let contentMode = imageView.contentMode
print("ContentMode is: \(contentMode)")

Result:

I tried making a String explicitly like this:

let description = String(describing: contentMode)
print("Description is: \(description)")

Which doesn't have any effect:

Is it only possible to print the value by switching over all the possible values?

switch contentMode {
case .scaleToFill:
    print("mode is scaleToFill")
case .scaleAspectFit:
    print("mode is scaleAspectFit")
case .scaleAspectFill:
    print("mode is scaleAspectFill")
case .redraw:
    print("mode is redraw")
case .center:
    print("mode is center")
case .top:
    print("mode is top")
case .bottom:
    print("mode is bottom")
case .left:
    print("mode is left")
case .right:
    print("mode is right")
case .topLeft:
    print("mode is topLeft")
case .topRight:
    print("mode is topRight")
case .bottomLeft:
    print("mode is bottomLeft")
case .bottomRight:
    print("mode is bottomRight")
@unknown default:
    print("default")
}

This finally gives me the result I want:

But this is really tedious, and I don't want to do this for every system enum if I can avoid it.

aheze
  • 24,434
  • 8
  • 68
  • 125
  • You can add extension on system enum and define description computed property, for exmple – Andrew Jan 12 '21 at 17:58
  • 1
    LLVM strips this metadata (the case labels) so they aren‘t available at runtime. Reflection or other runtime magic won‘t work here. You‘ll have to provide a custom implementation for `CustomStringConvertable` switching over the cases and return their labels manually :( – fruitcoder Jan 12 '21 at 18:58

1 Answers1

-1

If you go to the implementation of the Content Mode, you will notice that it is a Int Enum. This way, you always gets it index instead of a proper description:

Swift UIImageView ContentMode implementation

But this is weird, because you still should be able to get the enum name, and if you want the number, you call .rawValue. Instead, we receive the rawValue as default. Probably we get a computed variable instead of the proper variable.

The work around I propose is the same as you did, but as an extension of the original enum, creating a function that does the work for you, maintaining the abstraction:

ContentMode Enum extension

Have a great day!

  • Thanks for the answer, this makes sense! But it's not much of an improvement in terms of how much code you need to write... – aheze Jan 14 '21 at 00:48