如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
MyError
的Error
第一和带扩展它LocalizedError
以后呢?如果您LocalizedError
首先将其设置为有区别吗?