Skip to content
This repository has been archived by the owner on Oct 19, 2024. It is now read-only.

Converting AnyCodable to Any Struct Model #68

Open
alicankurtFinago opened this issue Apr 1, 2022 · 1 comment
Open

Converting AnyCodable to Any Struct Model #68

alicankurtFinago opened this issue Apr 1, 2022 · 1 comment

Comments

@alicankurtFinago
Copy link

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?

@makleso6
Copy link

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

2 participants