【问题标题】:Swift Declare generic type that conforms to a certain protocol in a dictionary [duplicate]Swift声明符合字典中某个协议的泛型类型[重复]
【发布时间】: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 以允许将字典的值传递给该函数?

注意:这两种方法只是我尝试但失败的示例。

【问题讨论】:

  • 希望有条件的一致性会对此有所帮助。当KeyValue 都是Codable 时,可以制作字典Codable
  • 你能用一些伪代码解释一下吗? container.encodeIfPresent(dic[key], forKey: key) 我希望 dic[key] 可以编码,但我怎样才能让编译器知道呢?
  • 对 Codable 有足够的了解,能够帮助解决这个问题:/

标签: swift dictionary generics encode


【解决方案1】:

我的问题可能与这个Store Encodables in a Swift Dictionary重复了

使用它的第一个解决方案,我成功了。

struct EncodableValue: Encodable {
    let value: Encodable

    func encode(to encoder: Encoder) throws {
        try value.encode(to: encoder)
    }
}


public struct JWTPayload: Codable {
    var customFields: [String: EncodableValue]?
}

//how to use it
payload.customFields = ["name": EncodableValue(value: "wang"),
                                "isAdmin": EncodableValue(value: true),
                                "age": EncodableValue(value: 125),
                                "height": EncodableValue(value: 181.5)]

【讨论】:

    猜你喜欢
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    相关资源
    最近更新 更多