Ios Swift结果类型能否返回动态错误消息?
在Swift中使用结果类型时,必须事先定义错误枚举Ios Swift结果类型能否返回动态错误消息?,ios,swift,Ios,Swift,在Swift中使用结果类型时,必须事先定义错误枚举 enum AppError: String, Error { case error1 = "Error One." case error2 = "Error Two." } 到目前为止,我可以列举我的应用程序或函数可能引发的所有可能错误。但是,我可能希望返回动态错误消息,例如从网络返回的错误消息。我找不到使用结果类型返回动态错误消息的方法。我不确定这是否可能 更新: 结果证明我根本不需要
enum AppError: String, Error {
case error1 = "Error One."
case error2 = "Error Two."
}
到目前为止,我可以列举我的应用程序或函数可能引发的所有可能错误。但是,我可能希望返回动态错误消息,例如从网络返回的错误消息。我找不到使用结果类型返回动态错误消息的方法。我不确定这是否可能
更新:
结果证明我根本不需要使用枚举。我只需要定义一个实现Error的类
我让它像这样工作:
class AppError: Error {
var message: String
init(_ message: String) {
self.message=message;
}
}
completion(.failure(AppError("Invalid URL.")))
error.message
要创建如下错误:
class AppError: Error {
var message: String
init(_ message: String) {
self.message=message;
}
}
completion(.failure(AppError("Invalid URL.")))
error.message
要像这样返回错误消息,请执行以下操作:
class AppError: Error {
var message: String
init(_ message: String) {
self.message=message;
}
}
completion(.failure(AppError("Invalid URL.")))
error.message
您可以定义错误类型,以获取可以在运行时设置的字符串参数
enum AppError: Error {
case decodingError(String)
case networkError(String)
}
关联值很好,但不幸的是,它们只适用于普通枚举。我建议不要使用字符串枚举,而是遵循CustomStringConvertible,并使用description属性返回错误的字符串值
enum AppError: Error, CustomStringConvertible {
case error1
case error2
case customError(message: String)
var description: String {
switch self {
case error1: return "Error 1"
case error2: return "Error 2"
case customError(let message): return message
}
}
}
谢谢它可以工作,但是如何从错误中获取原始字符串?error.localizedDescription返回的内容比原始字符串返回的内容多。@QianChen:可能有帮助:。@JoakimDanielson,我可以创建类似completion.failure.errorInvalid URL的错误,但当我收到相同的错误时,如何提取字符串无效URL。?用例。failurelet错误:获取创建结果时使用的错误对象