swift - 可编码的 [String: Any] 字典
问题描述
在我的代码中,我有一个具有 type 属性的类[String: Any]
。在实现Codable
协议时,编译器显示错误,说
Protocol type 'Any' cannot conform to 'Decodable' because only concrete types can conform to protocols
open class MMSDKNotification: Codable {
enum MMSDKNotificationKeys: String, CodingKey { // declaring our keys
case id = "id"
case message = "message"
case isRead = "isRead"
case creationTime = "creationTime"
}
public var id: Int = 0
public var message: [String: Any]?
public var isRead: Bool = false
public var creationTime: Int = 0
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: MMSDKNotificationKeys.self) // defining our (keyed) container
self.id = try container.decode(Int.self, forKey: .id)
// Here is the error:
// Protocol type 'Any' cannot conform to 'Decodable' because only concrete types can conform to protocols
self.message = try container.decode(String.self, forKey: .type)
self.isRead = try container.decode(Bool.self, forKey: .isRead)
self.creationTime = try container.decode(Int.self, forKey: .creationTime)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: MMSDKNotificationKeys.self)
try container.encode(id, forKey: .id)
try container.encode(isRead, forKey: .isRead)
try container.encode(creationTime, forKey: .creationTime)
}
}
可以Codable
和[String: Any]
字典一起使用吗?
解决方案
是否可以将 Codable 与 [String: Any] 字典一起使用?
不,您不能使用 Codable,但您可以在新模型中制作这本字典。
代替
公共变量消息:[字符串:任何]?
和
公共变量消息:MessageModel?
struct MessageModel: 可编码 { }
推荐阅读
- r - How to read in CSV file that has tab row delimiters and pipe '|' column delimiters?
- r - How to colour lines in vegan's rarecurve by factors?
- azure - 具有 IP 范围限制的 Azure Blob SAS
- algorithm - Specifying starting point for graph traversal algorithm in neo4j
- batch-file - How to answer automatically (Y/N) when prompt?
- c# - Oracle table getting locked when trying to write out a clob
- javascript - 如何使我的本地主机服务器可用于外部请求?
- r - 是否有直接进入包的功能索引帮助页面的命令?
- java - 交易传播问题
- javascript - 仅在执行完异步函数后如何转到循环中的下一项?