Search code examples
swift3swxmlhash

swxmlhash conditional deserialization that may return nil


I'm using SWXMLHASH Swift library to parse some 3rd party XML data. This data can sometimes be returned with values that are not valid for my application. When this happens I wish to ignore this data and return nil instead of Self in my deserialize function.

For example, I have some XML like this:

<Root>
    <ColourChanges>
        <ChangeCount>0</ChangeCount>
        <ChangeItems></ChangeItems>
    </ColourChanges>
</Root>

I want to be able to test the ChangeCount value, and if it equals 0 I want to be able to return nil in the deserialize function of my ColourChanges struct.

It appears that when I define my deserialize function as follows:

static func deserialize(_ node: XMLIndexer) throws -> ColourChanges?

I get a runtime error complaining the deserialize implementation doesn't exist.

I believe I could handle this by throwing from my struct's deserialize method when I encounter an unwanted value and handle that in the caller, however, it would be cleaner if I could just return nil.

Has anyone encountered a similar issue, or any suggestions on how this may be achieved?

Thanks for any help.


Solution

  • Adding my suggestion from above:

    A pattern I've used is cases like this is the null object pattern - basically you return something like ColourChanges.empty where empty is a method that builds a ColourChanges instance with preset values to indicate that it is empty or null. Would that work for you?