levantAJ / AnyCodable

Decode [String: Any] for Codable
MIT License
83 stars 14 forks source link

How to deal with custom type which conform to Codable protocol? #1

Open ywqqqqq opened 5 years ago

ywqqqqq commented 5 years ago

Hi guys, how could I encode a [String: Any] dictionary may contain a enum type which conform to Codable?

I has spent days on it. Any help will be appreciated.

skyfoxa commented 3 years ago

Hi @ywqqqqq,

I created this AnyEncodable struct so I can encode any type that conforms to Encodable protocol. https://github.com/levantAJ/AnyCodable/pull/5

For Decoding I have something like this:

struct MyType: Codable {}

fileprivate static func _decode(from dictRaw: [String: Any]) -> [String : MyType] {
        let decoder = JSONDecoder()
        return dictRaw.compactMapValues({ value -> MyType? in
            guard
                let dict = value as? [String : Any],
                let data = try? JSONSerialization.data(withJSONObject: dict),
                let object = try? decoder.decode(MyType.self, from: data)
            else {
                return nil
            }

            return object
        })
    }