Open alicankurtFinago opened 2 years ago
Hi @alicankurtFinago, my solution
import Foundation
import AnyCodable
extension Encodable {
public func transformToAnyCodable(
using encoder: JSONEncoder = JSONEncoder(),
decoder: JSONDecoder = JSONDecoder()
) throws -> AnyCodable {
try transform(to: AnyCodable.self, using: encoder, decoder: decoder)
}
public func transform<T>(
to type: T.Type,
using encoder: JSONEncoder = JSONEncoder(),
decoder: JSONDecoder = JSONDecoder()
) throws -> T where T: Decodable {
let data = try encoder.encode(self)
return try decoder.decode(type, from: data)
}
}
usage
LoginResponseModel(parameter: "").transformToAnyCodable()
Hi, I want to create generic/dynamic structure and convert AnyCodable to -> Login/Register/X Response Model.
I easily convert Model to AnyCodable like this -> AnyCodable( LoginResponseModel(parameter: "") ) However, if i want to convert AnyCodable to Model, i must follow this steps;
1- Converting Object To Json String 2- Converting Json String To Json Data 3- Converting Json Data To Model
Is there any easier way?