CGSize is encoded to an array by default. I would like to encode it to [String: Float] (i.e. ["width": 10, "height": 20]). Is there a way to override the default encoding/decoding behavior? Of course, as a workaround, I can define my own Dimension type and use that instead. I am just curious to know.
Swift - Override default encoding/decoding
615 views Asked by Jack Guo At
1
There is no supported way to outright override the encoding format for a given type you don't own; there are hacks that you can apply to override some types within your own module, but they're fragile and not worth employing.
If you use a 3rd-party encoder/decoder combo that isn't
Foundation.JSONEncoder/Foundation.JSONDecoder, it may offer an override facility similar to encoding/decoding strategies supported by Foundation, but that is dependent on the tools you're using.The "official" way to do this would be to either wrap
CGSizein a type you do own (as you suggest) and implementinit(from:)/encode(to:)there, or overrideinit(from:)/encode(to:)for all of the types that useCGSize(but this can get pretty tedious).