[swift-users] dealing with heterogenous lists/dictionary with Codable
David Baraff
davidbaraff at gmail.com
Thu Oct 19 10:10:56 CDT 2017
I’ll try. Is that cast smart enough to apply recursively? We shall see.
Sent from my iPad
> On Oct 19, 2017, at 7:34 AM, Geordie Jay <geojay at gmail.com> wrote:
>
> I mean can you do something along the lines of
>
> let codableDict = stringAnyDict as? [String : Codable]
>
> ?
>
> I’m not at a computer to test it myself
>
>
>
>
> David Baraff <davidbaraff at gmail.com> schrieb am Do. 19. Okt. 2017 um 15:45:
>> That’s exactly what I want. The ironic part is that I got my dictionary by decoding a Json file. If that’s where my dictionary came from, is there a simple way of coercing the Json serialization routines to give me back codables, rather than Anys?
>>
>>
>> Sent from my iPad
>>
>>> On Oct 19, 2017, at 3:38 AM, Geordie Jay <geojay at gmail.com> wrote:
>>>
>>>
>>> David Baraff via swift-users <swift-users at swift.org> schrieb am Do. 19. Okt. 2017 um 03:47:
>>>> So I have simple structs like this:
>>>>
>>>> struct Library: Codable {
>>>> let domain: String
>>>> let unit: String
>>>> }
>>>>
>>>> and it’s super-simple to serialize. Yay.
>>>>
>>>> But:
>>>>
>>>> struct LibraryGroup : Codable { // I wish...
>>>> let libraries: [Library]
>>>> let someDict: [String : Any]
>>>> }
>>>
>>> I haven’t tried this, but is it possible to have a dictionary of [String : Codable] ? Because that’s exactly the type requirements you’re describing, no?
>>>
>>> Geordie
>>>
>>>>
>>>> So what I’m looking for is something where if the values in someDict are themselves Codable, I can serialize things, and if they’re not, I can’t. In my previous scheme, I was using NSKeyedArchiver to serialize everything, manualy, including someDict; in trying to switch to Codable I ran smack into the fact that Codable wants to know what all the types are, in advance.
>>>>
>>>> Am I just stuck? How do I get the best of both worlds, where the compiler can make use of the fact that it can see the data types of my structures, while still being able to serialize heterogenous data like is found in LibraryGroup?
>>>>
>>>> Is my only alternative to write a custom coder for LibraryGroup? Is there any hope I could teach Codable what to do with
>>>> [String: Any]
>>>>
>>>> ?
>>>>
>>>>
>>>> _______________________________________________
>>>> swift-users mailing list
>>>> swift-users at swift.org
>>>> https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171019/bb5fabb7/attachment.html>
More information about the swift-users
mailing list