Flight-School / AnyCodable

Type-erased wrappers for Encodable, Decodable, and Codable values
https://flight.school/books/codable
MIT License
1.28k stars 132 forks source link

Add support for encoding any Encodable #63

Closed paulw11 closed 2 years ago

paulw11 commented 2 years ago

This PR adds minimal support for encoding any value that conforms to Encodable (#58). Tests have been updated for this case.

What is missing:

Equatable and Hashable support for a wrapped Codable Decodable support, however it does not make much sense to decode directly to AnyCodable anyway; You would decode the concrete type and then type erase to AnyCodable if required.

NoahKamara commented 2 years ago

Oh wow this is exactly what I needed right now :D good timing @paulw11

minacle commented 2 years ago

How about decoding? Will it decoded correctly?

paulw11 commented 2 years ago

As per my comment on the PR - What would be the semantics of decoding an AnyCodable - It is type erased. There are a (potentially) infinite number of concrete types that could be decoded when an object is encountered during the decoding process. The current implementation will decode an embedded object as a dictionary, which seems like a reasonable approach.

Hopefully when you are decoding something you know what you are decoding. If you don't know then you would need to implement your own decoding logic that determined the embedded type somehow.

Conceivably you could provide a list of potential types and when the decoder encountered an embedded object it could try and decode them, but there is a risk that if multiple types matched the object signature you would end up with the wrong thing.

minacle commented 2 years ago

I know it is redundant but please add the same test for decoding encoding into AnyEncodableTests.swift.

Thank you for your contributions.

paulw11 commented 2 years ago

Do you mean add code to the test to confirm that decoding the result of encoding gives the expected result?

This sounds like a reasonable test that should probably have been included in current test suite.

minacle commented 2 years ago

Oh, I am sorry. I meant, encoding, not decoding, and add same test into AnyEncodableTests.swift.

paulw11 commented 2 years ago

Oh ok. That makes more sense 😀

paulw11 commented 2 years ago

I have updated the AnyEncodableTests