0

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.

AlexM
  • 25
  • 5
  • 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? – David Mohundro May 04 '17 at 23:23
  • @DavidMohundro - Thank you for responding to the question. Your suggestion might be problematic in this use case, there are nodes returned from the XML where it _may_ entirely be made up of nil values (i.e. the associated WSDL with the XML doesn't mandate values), so I wonder whether this will cause issues attempting to come up with an _empty_ version. Currently, to work around, I'm using the 'throwing approach' I described in my post. However, this may also potentially hide issues because I'm using it in conjunction with `try?` during the `myobject.value()` call. I will investigate your idea. – AlexM May 06 '17 at 12:55
  • I've played with your suggestion a little, and the solution I've arrived at is to have a static function that returns ColourChanges?. I use this to wrap the call to value(). I can then test my object for validity and return nil if necessary. Please feel free to change your comment into an answer and I can mark it as correct. Thanks again for responding to the question. – AlexM May 07 '17 at 14:44

1 Answers1

0

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?

David Mohundro
  • 11,922
  • 5
  • 40
  • 44