如果 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/