[英]How to encode decode a struct that contains Dictionary
我想制作一個 struct Codable 以便我可以將內容寫入文件
struct LocationDetails: Codable {
var locationId: String? = nil
var providerId: String? = nil
var locationDict = [String:Any]()
var providerDict = [String:Any]()
}
給出錯誤:類型“LocationDetails”不符合協議“Decodable”。
如果我使用 Array 並使用 PropertyListEncoder 和 PropertyListDecoder 對結構進行編碼/解碼,而不是 Dictionary 它工作正常。 但是甚至不允許我在 codable 結構中定義字典如何使用 Dictionary Codable 制作結構?
您可以使用泛型定義結構,如下所示刪除Any
類型並將您的字典值類型限制為符合Codable
類型。
順便說一句:如果你只是保存(而不是加載),你應該使用Encodable
,而不是Codable
。
struct LocationDetails<Location: Codable, Provider: Codable>: Codable {
var locationId: String? = nil
var providerId: String? = nil
var locationDict = [String:Location]()
var providerDict = [String:Provider]()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.