Swift - Encode and Decode a dictionary [String:Any] into plist

前端 未结 2 1464
天涯浪人
天涯浪人 2021-01-17 05:00

I am trying to store the dictionary in my class Marker but it is throwing an error saying it is not encodable or decodable. I can see the error is caused by the [String: Any

2条回答
  •  执念已碎
    2021-01-17 05:25

    Unfortunately you cannot use encode or decode on generic types containing Any (e.g. [String: Any] or [Any]). Any does not conform to protocols Encodable nor Decodable and Swift doesn't know how to encode/decode it. You must use a concrete generic type for your dictionary (e.g. [String: String]).

    If you still need to use a general type like Any you have to implement encode(to:) and init(from:) methods. Another option would be to use a struct instead of your [String: [String: [String:Any]]] which conforms to Codable (Encodable & Decodable). You will still have to implement encode(to:) and init(from:) methods in that struct, but the bright side is that you will not have to write the encoder.encode() story for all the properties like you would have to if you implement them in the Marker class.

提交回复
热议问题