I have a need to wrap several kinds of objects into a dictionary say [String: Any?], but how do I tell that the Any? object is all Encodable?
let params: [String: Any?] = ["num": 123, "text": "abc", "obj": encodableobject]
JSONEncoder().encode(params) // compiler error because Any? is not Encodable
You just cannot.
What I do in such a case
- create an intermediate struct, Codable, with the different properties
- "num": Int, "text": String, "obj": Encodableobject
- convert the dict to such an object
- Now I can encode as JSON and decode and rebuild dictionary
If that may help :
- maybe with protocol extension: https://stackoverflow.com/questions/62252547/value-of-protocol-type-encodable-cannot-conform-to-encodable-only-struct-en ?
- interesting thread here: https://forums.swift.org/t/serializing-a-dictionary-with-any-codable-values/16676/10