Use Swift Encodable to encode additional properties as null without custom encoding

I want to encode an optional field with Swift JSONEncoderusing structone that conforms to the protocol Encodable.

By default, it JSONEncoderis determined that it uses the method encodeIfPresent, which means that the values ​​are nilexcluded from Json.

How can I override this for a single property without writing my custom function encode(to encoder: Encoder), in which I have to implement an encoding for all properties (for example, this article offers in the section "Custom Encoding")?

Example:

struct MyStruct: Encodable {
    let id: Int
    let date: Date?
}

let myStruct = MyStruct(id: 10, date: nil)
let jsonData = try JSONEncoder().encode(myStruct)
print(String(data: jsonData, encoding: .utf8)!) // {"id":10}
+6

All Articles