在Swift 3中获取ObjC枚举的名称吗? [英] Getting Name of ObjC Enum in Swift 3?

查看:124
本文介绍了在Swift 3中获取ObjC枚举的名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果ObjC函数返回带有枚举的状态值,是否可以在Swift 3中获取枚举的字符串?如果执行debugPrint("\(status)")print("\(status)"),我只会得到枚举的名称而不是值.如果我做status.rawValue,我会得到int,但这对解释没有多大的意义.

If an ObjC function returns a status value with enum, is there way to get the string of the enum in Swift 3? If I do debugPrint("\(status)"), or print("\(status)") I just get the name of the enum instead of value. If I do status.rawValue, I get the int, but it doesn't mean much to interpret.

推荐答案

您还可以将Obj-C枚举的符合性添加到CustomStringConvertible,然后以这种方式将值转换为字符串.只要您不使用default,这些值中的任何一个在以后的版本中都会更改时,您都会收到警告.

You can also add conformance of the Obj-C enum to CustomStringConvertible and translate values to strings that way. As long as you don't use default you will be warned if any of these values change in future versions.

例如:

extension NSLayoutAttribute : CustomStringConvertible {
    public var description: String {
        switch self {
        case .left : return "left"
        case .right : return "right"
        case .top : return "top"
        case .bottom : return "bottom"
        case .leading : return "leading"
        case .trailing : return "trailing"
        case .width : return "width"
        case .height : return "height"
        case .centerX : return "centerX"
        case .centerY : return "centerY"
        case .lastBaseline : return "lastBaseline"
        case .firstBaseline : return "firstBaseline"
        case .leftMargin : return "leftMargin"
        case .rightMargin : return "rightMargin"
        case .topMargin : return "topMargin"
        case .bottomMargin : return "bottomMargin"
        case .leadingMargin : return "leadingMargin"
        case .trailingMargin : return "trailingMargin"
        case .centerXWithinMargins : return "centerXWithinMargins"
        case .centerYWithinMargins : return "centerYWithinMargins"
        case .notAnAttribute : return "notAnAttribute"
        }
    }
}

这篇关于在Swift 3中获取ObjC枚举的名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆