Search code examples
swiftjsonencoder

Swift - Override default encoding/decoding


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.


Solution

  • 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 CGSize in a type you do own (as you suggest) and implement init(from:)/encode(to:) there, or override init(from:)/encode(to:) for all of the types that use CGSize (but this can get pretty tedious).