gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:54:27 26 4
gpt4 key购买 nike

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

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

但是有没有办法让它工作而不转换为我的错误类型?

最佳答案

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

Swift-defined error types can provide localized error descriptions by adopting the new LocalizedError protocol.

就您而言:

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协议(protocol),错误可以提供一个userInfo字典(还有一个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

关于swift - 如何在 Swift 中提供带有错误类型的本地化描述?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40590252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com