[swift-evolution] Is there a simple way to go from Codable to Any and vice versa?

Brent Royal-Gordon brent at architechies.com
Tue Aug 22 17:55:38 CDT 2017

> On Aug 22, 2017, at 12:32 PM, Youming Lin via swift-evolution <swift-evolution at 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?

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.

Brent Royal-Gordon

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170822/40d0e203/attachment.html>

More information about the swift-evolution mailing list