SwiftyLab / MetaCodable

Supercharge Swift's Codable implementations with macros meta-programming.
https://swiftpackageindex.com/SwiftyLab/MetaCodable/main/documentation/metacodable
MIT License
629 stars 23 forks source link

Support for customizing/removing nested key for enums with associated values? #30

Closed Sajjon closed 10 months ago

Sajjon commented 1 year ago

Hey! Great lib! Does it already support this use case?

struct StateHolder: Codable {
    let state: State
    enum State: Codable {
        case on(On)
        case off(Off)
        struct On: Codable {
            let onOnlyProperty: String
        }
        struct Off: Codable {
            let offOnlyProperty: String
        }
    }
}

when I JSON encode StateHolder(state: .on(.init(onOnlyProperty: "On!"))) Swift produces:

{
    "state" : {
        "on" : {
            "_0" : {
                "onOnlyProperty": "On!"
            }
        }
    }
}

Or using .off respectively:

{
    "state" : {
        "off" : {
            "_0" : {
                "offOnlyProperty": "Off!"
            }
        }
    }
}

Which is... well I think that was strange design decision by SE-0295.

I always manually change this to:

{
    "state" : {
        "discriminator": "on",
        "on" : {
            "onOnlyProperty": "On!"
        }
    }
}

Is this support by the lib? Or something you would consider adding?

soumyamahunt commented 1 year ago

Thanks @Sajjon, unfortunately generating Codable implementation for enums is not supported yet.

I would definitely consider adding support for enum. The major challenge is finding a generalized way of implementation that will work for all the users (which I am still figuring out). Let me know if you have anything in mind.

soumyamahunt commented 1 year ago

@Sajjon I have created #31 for discussing enum support, feel free to go through it and suggest any changes you would like with Enum types support

soumyamahunt commented 10 months ago

@Sajjon enum support has been released.