Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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 join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants