Let's say that I have a model like the following, which allows me to build a tree of Foo objects.
struct Foo {
var kind : Kind
enum Kind {
case node([Foo])
case leaf
}
}
How can I make this Codable, specifically for the case node([Foo])
?
Here is a great post of
Decoadable
protocol and its usage.I think at the bottom of the post in the Enum section you can find what you need, but if you don't want to read the article here is the gist which can be helpful.
One possible encoding for the
Foo
recursive data type could be:A simple test using the JSON encoder:
would then output the following JSON:
Conforming to
Decodable
should follow a similar logic ;)Here's the final struct, based on the answer from @PauloMattos:
Base Foo struct:
Codable Protocol extension:
CustomStringConvertable Protocol extension (to output string from the tree):
And example testing code:
Output: