Flight-School / AnyCodable

Type-erased wrappers for Encodable, Decodable, and Codable values
https://flight.school/books/codable
MIT License
1.28k stars 132 forks source link

How to encode object with AnyCodable #56

Closed Steven4294 closed 3 years ago

Steven4294 commented 3 years ago

I am using Vapor, though I don't believe that matters. I'm trying to pass in an object something that conforms to AnyEncodable See code:

let dic: [String: AnyEncodable] = [
    "number": 1,
    "string": "2020-10-01",
    "isBool": true,
    "post": Post(payload: "")
]
try req.content.encode(dic, as: .urlEncodedForm)

And my post object

struct Post {
    let payload: String
}

How do I make Post conform to AnyEncodable, so I can pass in an object as a value in my dictionary like such?

Additionally, I've tried:

KLPayload(
            token: "",
            time: 0,
            customer_properties: [
                "email": checkout.email
            ]
)

struct KLPayload: Encodable  {
    let token: String
    let time: Int
    let customer_properties: [String: AnyEncodable]
}

And I get Cannot convert value of type 'String' to expected dictionary value type 'AnyEncodable'

minacle commented 3 years ago

How do I make Post conform to AnyEncodable, so I can pass in an object as a value in my dictionary like such?

Just mark your struct as Encodable.

struct Post: Encodable {
    let payload: String
}

I get Cannot convert value of type 'String' to expected dictionary value type 'AnyEncodable'

Due to the type of checkout.email is String, you cannot insert it directly without wrapping with the AnyEncodable initialiser.

KLPayload(
    token: "",
    time: 0,
    customer_properties: [
        "email": .init(checkout.email)
    ]
)

struct KLPayload: Encodable {
    let token: String
    let time: Int
    let customer_properties: [String: AnyEncodable]
}