Best way to deserialize optional elements... #247
-
I have an array an array of elements and each of the nodes have potentially optional elements. This kind of makes a mess of the simple deserialization. I wonder if anyone has advice for a cleaner way of doing this. For example:
And the struct I'm deserializing into (eliding the sub types):
So as you can see, I am checking to see if the tie element is there (the one that only appears in note id=0 but not id=1) and if it is there I am getting the value(). Now, the first problem is that node["Tie"] throws for all of the Notes that don't have the Tie element. Is this a problem? I sure would like a way to index that returns an optional instead of throwing (or returning an xmlError case). All suggestions are welcome. This works fine, but seems inelegant and like I haven't RTFM'ed enough. TIA |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Any reason you're not using the struct Note: XMLIndexerDeserializable {
var id: Int
var tie: Tie?
var instrumentArticulation: Int
var properties: [NoteProperty]
static func deserialize(_ node: XMLIndexer) throws -> Self {
return try Note(
id: node.value(ofAttribute: "id"),
tie: node["Tie"].value(),
instrumentArticulation: node["InstrumentArticulation"].value(),
properties: node["Properties"]["Property"].value()
)
}
} Disclaimer: I haven't tried running this code, so it might have some issues... |
Beta Was this translation helpful? Give feedback.
-
Not sure what I was doing wrong, but this works fine. TY For the sanity check. |
Beta Was this translation helpful? Give feedback.
Any reason you're not using the
tie: node["Tie"].value()
there like below? The deserializer can handle optionals like this (if the left side is optional anyway):Disclaimer: I haven't tried running this code, so it might have some issues...