【问题标题】:How to access Swift property from custom Error?如何从自定义错误中访问 Swift 属性?
【发布时间】:2019-11-04 12:35:59
【问题描述】:

代码:

enum SHError: Error {

    case InvalidInputError(code: Int, message: String, info: [String:Any]? = [:])
    case InvalidProcessingError(code: Int, message: String, info: [String:Any]? = [:])

    var debugDescription: String {
        return "debug info: code: \(code)"
    }
    var localizedDescription: String {
        return "description: \(self)"
    }
}

如何在创建错误时访问调用者传递的属性?

【问题讨论】:

  • 请不要将您的代码发布为打印屏幕,复制并粘贴它(并可能添加错误评论)
  • 真正的麻烦是整个枚举设计得很糟糕。错误已经有代码,如果您还想要一条消息,您应该使用本地化错误。
  • enum 案例没有任何意义。如果您想在声明/使用时分配codemessageinfo,而不是enum,您最好需要struct/class。更好的是,您已经拥有满足您所有要求的NSError 类(NSError.init(domain: String, code: Int, userInfo: [String : Any]))。你可以查看这个官方documentation 了解如何使用enum 进行错误处理。
  • @bazyl87 我还包含原始源代码

标签: swift error-handling compiler-errors nserror


【解决方案1】:

如果你想使用与枚举大小写关联的值,你必须以这种方式切换它:

enum SHError: Error {

    case InvalidInputError(code: Int, message: String, info: [String:Any]? = [:])
    case InvalidProcessingError(code: Int, message: String, info: [String:Any]? = [:])

    var debugDescription: String {
        let code: Int
        switch self {
        case .InvalidInputError(code: let codeValue, message: _, info: _):
            code = codeValue
        case .InvalidProcessingError(code: let codeValue, message: _, info: _):
            code = codeValue
        }
        return "debug info: code: \(code)"
    }

    var localizedDescription: String {
        return "description: \(self)"
    }
}

或者您可以创建一个单独的计算变量var code: Int 并在debugDescription 中使用它:

enum SHError: Error {

    case InvalidInputError(code: Int, message: String, info: [String:Any]? = [:])
    case InvalidProcessingError(code: Int, message: String, info: [String:Any]? = [:])

    var debugDescription: String {
        return "debug info: code: \(code)"
    }

    var localizedDescription: String {
        return "description: \(self)"
    }

    var code: Int {
        switch self {
        case .InvalidInputError(code: let code, message: _, info: _):
            return code
        case .InvalidProcessingError(code: let code, message: _, info: _):
            return code
        }
    }
}

【讨论】:

  • @Sazzad Hissain Khan 我已经更新了答案以匹配您的枚举
猜你喜欢
  • 2019-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 2012-06-05
  • 1970-01-01
  • 1970-01-01
  • 2021-03-13
相关资源
最近更新 更多