首页 > 解决方案 > 从 '(_) throws -> ()' 类型的抛出函数到非抛出函数类型 '(Response) -> Void' 的无效转换

问题描述

我需要像这样处理 api 错误代码并为某些状态代码抛出错误。但是下面的代码显示了上述错误。我怎样才能做到这一点?

func login(data: [String: Any], completion: @escaping (ResponseModel<SignUpModel>?) -> Void) throws {
        NetworkAdapter.request(target: .login(data: data), success: { (response) in

            if let responseModel =  try? JSONDecoder().decode(ResponseModel<SignUpModel>.self,from: response.data) {
                switch responseModel.statusCode {
                case 2000:
                    completion(responseModel)
                case 4005:
                    throw ValidationError.athenticationFailure
                case .none,.some:
                    break
                }
                completion(responseModel)
            } else {
            }
        })
    }

标签: iosswifterror-handling

解决方案


你不能

throw ValidationError.athenticationFailure

因为请求是异步的。您可以做的是将完成类型更改Result<ResponseModel<SignUpModel>, ValidationError>为返回

completion(.success(responseModel))

关于成功和

completion(.failure(athenticationFailure)

关于失败。顺便说一句,我买了一个u


推荐阅读