结果中的.failed(let e)条件返回,并带有SDKError枚举下的自定义异常列表。在UI方面,我必须为不同类型的故障实现逻辑。如何从对象中识别错误类型?
case .failed(让e as!SDKError):
.failed(let e): e.localizedDescription
// UI side implementation
SDK.getInstance.fetchItems() { (result) in
switch result {
case .success(let item):
self.item = item
case .failed(let e):
print("Error=\(e)")
}
}
// SDK part
// Type of response from the closure
public enum ResultModel<T, E> {
case success(T)
case failed(E)
var isSuccess: Bool {
if case .success(_) = self {
return true
}
return false
}
var isFailed: Bool {
if case .failed(_) = self {
return true
}
return false
}
}
// SDK part
// Enum class for different exceptions
public enum SDKError: Error {
case UnacceptableStatusCode(Int)
case UnexpectedResponse(Any)
case InvalidAuthCredentials(Any)
case InvalidData(Any)
case MandatoryPasswordReset(Any)
case NullDataFound(Any)
case NullResponse(Any)
}
答案 0 :(得分:2)
您可以将错误类型调度switch
嵌套在另一个switch
内,以区分成功与错误状态:
switch result {
case let .failed(error):
switch error {
case let SDKError.UnacceptableStatusCode(code): // ...
// other cases go here
}
case let .success(value):
// success handling goes here
}