在 Swift 中获取 Objective-C @objc 枚举值的字符串名称? [英] Getting String name of Objective-C @objc enum value in Swift?

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

问题描述

如果一个 Objective-C 函数返回一个带有 enum 的状态值,有没有办法在 Swift 中获取 enum 的字符串?

If an Objective-C function returns a status value with enum, is there a way to get the string of the enum in Swift?

询问同样的问题本机 Swift 枚举案例,但在这个问题中,我专门使用 @objc enum Swift 中的 Objective-C 枚举:

The same question is asked of native Swift enumeration cases, but in this question I am specifically working with @objc enum Objective-C enums in Swift:

如果我执行 debugPrint("\(status)")print("\(status)") 我只会得到枚举而不是值.

If I do debugPrint("\(status)") or print("\(status)") I just get the name of the enum instead of value.

如果我执行 status.rawValue,我会得到 int,但解释起来没有多大意义.

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 中获取 Objective-C @objc 枚举值的字符串名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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