Flight-School / AnyCodable

Type-erased wrappers for Encodable, Decodable, and Codable values

Home Page:https://flight.school/books/codable

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Converting AnyCodable to Any Struct Model

alicankurtFinago opened this issue · comments

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?

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()