jl3*_*303 6 objective-c swift3
如果一个ObjC函数返回一个带枚举的状态值,有没有办法在Swift 3中获取枚举的字符串?如果我这样做debugPrint("\(status)"),或者print("\(status)")我只是得到枚举的名称而不是值.如果我这样做status.rawValue,我会得到int,但解释并不多.
Objective-C enumcase的名称在运行时不存在——它们只是整数值,不像 Swift 的enums,它们具有与其关联的运行时信息。如果您想在运行时获得单个案例的名称,您将必须单独存储它们并通过整数值访问它们(即从 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"
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1031 次 |
| 最近记录: |