Codable Dictionary with Any as values

I have 2 structs, Struct1, Struct2, which are both Codable.


When I try to encode a Dictionary which has both structs as values:

typealias DataFileDictionary = [String: Any]
var st1 = Struct1(…)
var st2 = Struct2()
        let dictForSave : DataFileDictionary = ["DataSettings": st1, "AllData": st2]
        let json = try? JSONEncoder().encode(dictForSave)


I get the following error on line 5:


Generic parameter 'T' could not be inferred.


Is iy forbidden to have such pattern ?


I've read some solutions, with registering the types…

h ttps://medium.com/makingtuenti/indeterminate-types-with-codable-in-swift-5a1af0aa9f3d

Really complex (seem overkill in my case)


I though it could be possible to declare that Any is Codable,

something like

typealias DataFileDictionary = [String: Codable]

but could not find how to express it.


I can use a struct instead, but that does not seem as clean.

Answered by QuinceyMorris in 351092022

It fails because there's no conversion from [String: Any] to [String: T] where T: Codable. This:


typealias DataFileDictionary = [String: Codable]


doesn't work either, because that type doesn't itself conform to Codable. (Protocol Codable, like all protocols, doesn't conform to itself.)


You can take this to the Swift forums for other opinions, but I'd suggest using the enum approach described in that medium post, is a fairly straightforward way to do this.

Accepted Answer

It fails because there's no conversion from [String: Any] to [String: T] where T: Codable. This:


typealias DataFileDictionary = [String: Codable]


doesn't work either, because that type doesn't itself conform to Codable. (Protocol Codable, like all protocols, doesn't conform to itself.)


You can take this to the Swift forums for other opinions, but I'd suggest using the enum approach described in that medium post, is a fairly straightforward way to do this.

Codable Dictionary with Any as values
 
 
Q