1

I am using this function

public mutating func encodeIfPresent<T>(_ value: T?, forKey key: KeyedEncodingContainer.Key) throws where T : Encodable

to encode a entity

But my entity contains a dictionary which I also want to use that function to encode

encodeIfPresent accept a generic value that conforms to Encodable protocol.

How can I declare my dictionary like var customFields: [String: Encodable.Type]? or var customFields: [String: T] where T : Encodable to allow the values of the dictionary to be passed to that function?

note: the two methods are just examples which I tried but failed.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Wstunes
  • 196
  • 1
  • 9
  • Hopefully conditional conformances will help with this. Dictioanries can be made `Codable` when `Key` and `Value` are both `Codable` – Alexander Jan 22 '18 at 05:22
  • Could you explain this with some pseudo code? `container.encodeIfPresent(dic[key], forKey: key)` I want `dic[key]` to be codable but how can I let the compiler know it? – Wstunes Jan 22 '18 at 06:14
  • Idk enough about Codable to be able to help with this :/ – Alexander Jan 22 '18 at 06:44

1 Answers1

0

My question is probably duplicated to this one Store Encodables in a Swift Dictionary

Using its first solution, I made it.

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)]
Wstunes
  • 196
  • 1
  • 9