我正在使用 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鈥檛 be completed. (MyError error 0.)"
有没有办法localizedDescription返回我的自定义错误描述(“错误的用户友好描述。”)?请注意,这里的错误对象是 typeError而不是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 domainand 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