Custom coders

sorry if that was already asked,

is this possible in Swift 5 to create my own custom encoder/decoder pair for arbitrary structs that confirm to Codable protocol? if there's a sample code please point me to that.

let data = MyCoder().encode(value of ArbitraryCodableType)
let object = MyDecoder().decode(ArbitraryDecodableType.self, from: data)

the specifics of ArbitraryCodableType are not known to me at the point of implementing MyCoder / MyDecoder, only the fact that it is Codable

I implemented ones some time ago.

CSVCoder is probably more complete than BinaryCoder.
IMO, the important part is figuring out what for you're encoding to/decoding from.
The rest is just following the required conformance, and deciding whether you should support KeyedEn\Decoder, UnkeyedEn\Decoder, SingleValueEn\Decoder.

With that said, I see you have tagged this with json. Are you trying to convert to/from json file? If so, is there a reason you don't want to use Foundation's JSONEn/Decoder?

1 Like

thank you for that reference, will study.

"json" is just a tag.
it is a dictionary i want to convert to/from in this instance.
later on i'm also thinking doing this for xml.

There's also Foundation's JSONEn/Decoder

which I used as a guide.

I find xml tricky as you can have attributes inside the tag, as well as content between start & finish tag, which I have trouble expressing as Codable. Though with small enough scope, that shouldn't be a problem.

1 Like

yours is shorter :-) and easier to follow.

DictionaryCoder ought to be part of the system, IMHO.

the xml i'm looking next - is simple and under my control, i don't have to support arbitrary complex xml's.

1 Like