Is there a simple way to go from Codable to Any and vice versa?

Hi all

With Swift 4 Codable support, we can now do the following conversions:

  1. Codable <-> Data using JSONEncoder/JSONDecoder
  2. Any <-> Data using JSONSerialization

Not sure if I missed something obvious, but is there a simple way to do Codable <-> Any conversions? I can do Codable <-> Data <-> Any conversions to get the same results, but I doubt that's an efficient method to achieve my needs.

Looking through Foundation source code, I believe the fileprivate class _JSONDecoder enables the Any -> Codable conversion that I want:
https://github.com/apple/swift/blob/master/stdlib/public/SDK/Foundation/JSONEncoder.swift#L867-L868

However, it's not public and hence not currently usable in my code without copy/pasting the source code from Foundation to my package.

Youming Lin

Well, any type can be cast to `Any`, but I don't think that's what you have in mind.

What exactly do you want to do? Convert arbitrary types into the arrangement of strings, numbers, bools, arrays, and dictionaries that JSON would use, but not actually serialize that out to JSON? There's nothing built-in that will do that, but you can either apply JSONEncoder to make a Data and then JSONSerialization to decode it back into that data structure, or write a custom coder that mimics the JSONEncoder. Since JSONEncoder and JSONDecoder are open source, you could even use their source code as a starting point.

···

On Aug 22, 2017, at 12:32 PM, Youming Lin via swift-evolution <swift-evolution@swift.org> wrote:

Hi all

With Swift 4 Codable support, we can now do the following conversions:
Codable <-> Data using JSONEncoder/JSONDecoder
Any <-> Data using JSONSerialization

Not sure if I missed something obvious, but is there a simple way to do Codable <-> Any conversions?

--
Brent Royal-Gordon
Architechies