简体   繁体   English

有没有办法在Swift中为ErrorType值指定错误代码?

[英]Is there a way to specify an error code for an ErrorType value in Swift?

In my app I am using a custom error type ProgrammerError with three error values .Messiness , .Procrastination and .Arrogance (these are just examples). 在我的应用程序中,我使用自定义错误类型ProgrammerError其中包含三个错误值.Messiness.Procrastination.Arrogance (这些只是示例)。 Later in the code I need to cast the errors to NSError . 稍后在代码中我需要将错误转换为NSError The NSError objects have code properties starting from 0 following the order or error values I declared: 0, 1, 2 etc. 在我声明的顺序或错误值之后, NSError对象的code属性从0开始:0,1,2等。

enum ProgrammerError: ErrorType {
  case Messiness
  case Procrastination
  case Arrogance
}

(ProgrammerError.Messiness as NSError).code // 0
(ProgrammerError.Procrastination as NSError).code // 1
(ProgrammerError.Arrogance as NSError).code // 2

My question is : Is there a way to set different error codes for the enumeration values? 我的问题是 :有没有办法为枚举值设置不同的错误代码? For example, can I set Messiness to have code value of 100 instead of 0? 例如,我可以将Messiness设置为code值为100而不是0吗?

You can implement var _code: Int { get } property. 您可以实现var _code: Int { get }属性。

enum ProgrammerError: ErrorType {
    case Messiness
    case Procrastination
    case Arrogance

    var _code: Int {
        switch self {
        case .Messiness:
            return 100
        case .Procrastination:
            return 101
        case .Arrogance:
            return 102
        }
    }
}

(ProgrammerError.Messiness as NSError).code // 100
(ProgrammerError.Procrastination as NSError).code // 101
(ProgrammerError.Arrogance as NSError).code // 102

You can also implement var _domain: String { get } if you need. 如果需要,您还可以实现var _domain: String { get }

But I must warn you, these methods are undocumented so they might stop working in future. 但我必须警告你,这些方法没有记录,所以他们将来可能会停止工作。

Or, you may try explicit conversion. 或者,您可以尝试显式转换。

extension FileActionError {
    func getCode() -> Int {
        switch self {
        case .BadFileNodeIndex:     return 1
        case .BadFileNodePath:      return 2
        }
    }
    func toNSError() -> NSError {
        return NSError(domain: "", code: getCode(), userInfo: [NSLocalizedDescriptionKey: "\(self)"])
    }
}

Might not what you expected. 可能不是你所期望的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM