Suppose You have two kind of response like one for success and one for failure
Success response model will looks like
struct UserLogin: Codable {
let status: Bool?
let accessToken: String?
let data: [UserLoginData]?
....
}
Failure Model will looks like
struct FailedResponse: Codable {
let status: Bool?
let error: ErrorResponse?
}
How I handle this two responses
struct FailableResponse <T:Codable,E:Codable> : Codable {
var success:T?
var failure:E?
public init(from decoder:Decoder) throws {
let singleValue = try decoder.singleValueContainer()
success = try singleValue.decode(T.self)
failure = try singleValue.decode(E.self)
}
}
And How I use FailableResponse
APIClient.login(userName: self.loginViewModel.userName, password: self.loginViewModel.password) { (response:FailableResponse<UserLogin,FailedResponse>? , error) in
}
// METHOD OF API CLIENT
// API CALLING
static func login<T:Codable>(userName:String,password:String,completion:@escaping completionResponse<T>) {
self.performRequest(request: APIRouterUserModule.login(email: userName, password: password)) {(model) in
self.handleResponseCallCompletion(result: model, completion: completion)
}
}
// Parsing
private static func handleResponseCallCompletion<T:Codable>(result:Result<Any>,completion:@escaping completionResponse<T>) {
let object = CodableHelper<T>().decode(json: result)
completion(object.object,object.error)
}
I think It can be more better
Any suggestion Please :)