Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 views
in Technique[技术] by (71.8m points)

ios - Printing description of system enum value only prints the enum name

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: image

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: image

I tried making a String explicitly like this:

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

Which doesn't have any effect: image

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: image

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...