ml-archive / Serpent

A protocol to serialize Swift structs and classes for encoding and decoding.

Home Page:https://nodes-ios.github.io/Serpent/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature request to mark properties as required

cglarsen opened this issue · comments

The basic idea is that on the model level, you can mark one or more properties to be required so if in the incoming raw response they are not present stop the decoding and return empty struct/dictionary.

This could be a great addition to Serpent. 👍🏻

I was thinking a bit about how we could do this and the only way I can think of is defining new operators/functions that take a new parameter - an option set specifying the required state (or other options) of a given property. That enum could look something like this:

struct PropertyOptions: OptionSet {
    let rawValue: Int
    static let required = PropertyOptions(rawValue:  1 << 0)
}

So for example, this would change:

title         <== (self, dictionary, "title")

to this:

title         <== (self, dictionary, "title", [.required])

for a property that would need to be required. Ideally this thing would be optional, so that we maintain backwards compatibility and also make the code less cluttered and easier to read.

And as for how we would handle this internally - I am not a big fan of failable or throwing initializers for models, but it would have to be one of these options. I'm open to any suggestions, as I haven't yet made up my mind about what would be a better option. :D