swift - 在 Swift 中获取 Objective-C @objc 枚举值的字符串名称?

标签 swift objective-c

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

same question被问及 native Swift 枚举案例,但在这个问题中,我专门使用 @objc enum Objective-C enums in Swift :

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

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

最佳答案

您还可以将 Obj-C 枚举的一致性添加到 CustomStringConvertible 并以这种方式将值转换为字符串。只要您不使用 default,如果这些值中的任何一个在未来版本中发生变化,您将收到警告。

例如:

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 - 在 Swift 中获取 Objective-C @objc 枚举值的字符串名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40828769/

相关文章:

sql - 选择sqlite(Swift)中的count(col_name)不起作用

swift - 添加阴影以仅用两个带半径的角进行 View

iOS MapKit - showAnnotations 以在 Zoom 上包含用户位置

iphone - 像 Cocoa 一样抽象 UIViewController

ios - translatesAutoresizingMaskIntoConstraints 和 UILabel

objective-c - 使用 UIScrollView subview 调整 UIView 的大小

ios - 使用 iOS 10.2 版在同一设备上获取不同的 UUID

ios - TabView 中的 NavigationView 弹出时会使应用程序崩溃

ios - 为什么允许在实现内部的@interface中重写ivar,但是具有这种奇怪的行为?

ios - UIBarButtonItem : Image offsets