【发布时间】:2018-06-30 16:29:33
【问题描述】:
我正在使用这个功能
public mutating func encodeIfPresent<T>(_ value: T?, forKey key: KeyedEncodingContainer.Key) throws where T : Encodable
对实体进行编码
但我的实体包含一个字典,我也想使用该函数进行编码
encodeIfPresent 接受符合 Encodable 协议的通用值。
如何声明我的字典,如 var customFields: [String: Encodable.Type]? 或 var customFields: [String: T] where T : Encodable 以允许将字典的值传递给该函数?
注意:这两种方法只是我尝试但失败的示例。
【问题讨论】:
-
希望有条件的一致性会对此有所帮助。当
Key和Value都是Codable时,可以制作字典Codable -
你能用一些伪代码解释一下吗?
container.encodeIfPresent(dic[key], forKey: key)我希望dic[key]可以编码,但我怎样才能让编译器知道呢? -
对 Codable 有足够的了解,能够帮助解决这个问题:/
标签: swift dictionary generics encode