为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Swift中提供带有Error类型的本地化描述?

如何在Swift中提供带有Error类型的本地化描述?

Cats萌萌 2019-08-26 10:55:22
如何在Swift中提供带有Error类型的本地化描述?我正在使用Swift 3语法定义自定义错误类型,我想提供一个用户友好的错误描述,该描述由对象的localizedDescription属性返回Error。我该怎么做?public enum MyError: Error {   case customError  var localizedDescription: String {     switch self {     case .customError:       return NSLocalizedString("A user-friendly description of the error.", comment: "My error")     }   }}let error: Error = MyError.customError error.localizedDescription// "The operation couldn’t be completed. (MyError error 0.)"有没有办法让localizedDescription我返回我的自定义错误描述(“用户友好的错误描述。”)?请注意,此处的错误对象是类型Error而不是MyError。当然,我可以将对象强制转换为MyError(error as? MyError)?.localizedDescription但是有没有办法让它工作而不会转换为我的错误类型?
查看完整描述

3 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞


如Xcode 8 beta 6发行说明中所述,


Swift定义的错误类型可以通过采用新的LocalizedError协议提供本地化的错误描述。


在你的情况下:


public enum MyError: Error {

    case customError

}


extension MyError: LocalizedError {

    public var errorDescription: String? {

        switch self {

        case .customError:

            return NSLocalizedString("A user-friendly description of the error.", comment: "My error")

        }

    }

}


let error: Error = MyError.customError

print(error.localizedDescription) // A user-friendly description of the error.

如果错误转换为NSError(始终可以),您可以提供更多信息:


extension MyError : LocalizedError {

    public var errorDescription: String? {

        switch self {

        case .customError:

            return NSLocalizedString("I failed.", comment: "")

        }

    }

    public var failureReason: String? {

        switch self {

        case .customError:

            return NSLocalizedString("I don't know why.", comment: "")

        }

    }

    public var recoverySuggestion: String? {

        switch self {

        case .customError:

            return NSLocalizedString("Switch it off and on again.", comment: "")

        }

    }

}


let error = MyError.customError as NSError

print(error.localizedDescription)        // I failed.

print(error.localizedFailureReason)      // Optional("I don\'t know why.")

print(error.localizedRecoverySuggestion) // Optional("Switch it off and on again.")

通过采用该CustomNSError协议,错误可以提供userInfo字典(以及a domain和code)。例:


extension MyError: CustomNSError {


    public static var errorDomain: String {

        return "myDomain"

    }


    public var errorCode: Int {

        switch self {

        case .customError:

            return 999

        }

    }


    public var errorUserInfo: [String : Any] {

        switch self {

        case .customError:

            return [ "line": 13]

        }

    }

}


let error = MyError.customError as NSError


if let line = error.userInfo["line"] as? Int {

    print("Error in line", line) // Error in line 13

}


print(error.code) // 999

print(error.domain) // myDomain


查看完整回答
反对 回复 2019-08-26
?
慕虎7371278

TA贡献1802条经验 获得超4个赞

我还要补充一下,如果你的错误有这样的参数

enum NetworkError: LocalizedError {
  case responseStatusError(status: Int, message: String)}

您可以在本地化描述中调用这些参数,如下所示:

extension NetworkError {
  public var errorDescription: String? {
    switch self {
    case .responseStatusError(status: let status, message: let message):
      return "Error with status \(status) and message \(message) was thrown"
  }}

你甚至可以这样缩短:

extension NetworkError {
  public var errorDescription: String? {
    switch self {
    case let .responseStatusError(status, message):
      return "Error with status \(status) and message \(message) was thrown"
  }}


查看完整回答
反对 回复 2019-08-26
?
森栏

TA贡献1810条经验 获得超5个赞

使用结构可以是一种替代方案。静态本地化有点优雅:

import Foundationstruct MyError: LocalizedError, Equatable {

   private var description: String!

   init(description: String) {
       self.description = description   }

   var errorDescription: String? {
       return description   }

   public static func ==(lhs: MyError, rhs: MyError) -> Bool {
       return lhs.description == rhs.description   }}extension MyError {

   static let noConnection = MyError(description: NSLocalizedString("No internet connection",comment: ""))
   static let requestFailed = MyError(description: NSLocalizedString("Request failed",comment: ""))}func throwNoConnectionError() throws {
   throw MyError.noConnection}do {
   try throwNoConnectionError()}catch let myError as MyError {
   switch myError {
   case .noConnection:
       print("noConnection: \(myError.localizedDescription)")
   case .requestFailed:
       print("requestFailed: \(myError.localizedDescription)")
   default:
      print("default: \(myError.localizedDescription)")
   }}


查看完整回答
反对 回复 2019-08-26
  • 3 回答
  • 0 关注
  • 938 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信