一尘不染

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

swift

我正在使用Swift
3语法定义一个自定义错误类型,我想提供localizedDescriptionError对象的属性返回的错误的用户友好描述。我该怎么做?

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

但是有没有办法在不强制转换为我的错误类型的情况下使它工作?


阅读 247

收藏
2020-07-07

共1个答案

一尘不染

如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 domaincode)。例:

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
2020-07-07