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.

Powered by WPeMatico

You may also like...

Comments are closed.