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

Arbitrary Codable

shaps80 opened this issue · comments

commented

@mattt Welcome back the OSS world and congrats on your book(s). Looking great so far.

I used this approach earlier today to add Codable support to a LinkedList with arbitrary values.

Your implementation works great for known Swift types but I'm wondering if its possible to encode/decode any value that conforms to Codable?

I gave it a shot and can get it to compile by adding:

public func encode(to encoder: Encoder) throws {
    // ...
    case let value as Codable:
            try container.encode(AnyEncodable(value))
    //...
}

Which compiles but when I try to encode (haven't tackled decoding yet) I get a runtime crash because AnyEncodable ends up being called recursively.

Any ideas would be appreciated :)