Last time we looked at creating one-off factories that we can use to
parse collections of subclass objects with Gloss. But it’s a drag
to have to put the Factory boilerplate in multiple places and define
separate decoders for each group of types.
This time we’re going to take a step back and use generics to abstract out
the Factory…
Here is our Factory. It knows the keyPath to look at to find the
type identifier in a JSON block, and it has a table of subtypes to
create based on what it finds there.
Our subtypes should implement this protocol, which lets us
discover the factory that we should use to make them:
Ideally, we’d specify that the Output of the factory is a
FactoryDecodable, not just a Decodable, but we can’t use the protocol
as a requirement of itself.
Our supertype defines the factory itself.
There’s still nothing special in our subtypes…
Our subtypes must be registered with the supertype’s Factory.
And now the Glossy part… Decoders that look for FactoryDecodables
and collections of them:
And operators to make those nicer to use…
It would be nice to be able to use the <~~ operator that Gloss uses,
but that gives us a “Type of expression is ambiguous without more context”
error. I’m not sure why that is, since FactoryDecodable is more specific
than Decodable.
Now we can have a Decodable class that contains arbitrary collections
of Shapes.