我正在使用Swift 3语法定义一个自定义错误类型,我想提供localizedDescription该Error对象的属性返回的错误的用户友好描述。我该怎么做?
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
MyError
(error as? MyError)?.localizedDescription
但是有没有办法在不强制转换为我的错误类型的情况下使它工作?
如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(总是可能的):
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)。例:
CustomNSError
userInfo
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