Encode struct

I have many structs like Item
When I encode this struct I need to pick up just value field from StringField

struct Item: IModel{    
    var camera : StringField    
    var globe : StringField

    enum CodingKeys: String, CodingKey {
        case camera
        case globe

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(camera.value, forKey: .camera)
        try container.encode(globe.value, forKey: .globe)

public struct StringField: IField {
    var value: String

You might have come across the case and can give me a hint how to automate encode function and not to write encode(to encoder: Encoder) or even CodingKeys manually for every model like Item ?

I think you instead can create custom encode(to:) and init(from:) implementations for StringField. That way, you don't need to poke into .value for all use sites, but only for the inner type.


Thank you for the hint, works perfectly :slight_smile:

public func encode(to encoder: Encoder) throws {
    var container = encoder.singleValueContainer()
    try container.encode(value)
1 Like