SwiftyLab / MetaCodable

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

[Feature Request] Encodable Default Value Handling #77

Closed tatewake closed 5 months ago

tatewake commented 5 months ago

Is your feature request related to a problem? Please describe.

In my scenario, I need to assign default values during decoding if certain fields are missing (which is already supported), but I also want to avoid encoding a field if its value matches the same default.

Consider this Node struct:

@Codable
struct Node: Hashable {
    @Default("")
    var label: String = ""
    @Default(CGPoint.zero)
    var center: CGPoint = .zero
}

For example, if center isn't set, it should default to .zero during decoding. Similarly, for my use case, if it's already set to .zero, there's no need to encode it since it's the expected default.

Describe the solution you'd like Introduce a new tag, perhaps something like @IgnoreEncodingIfDefault when set alongside @Default(CGPoint.zero) or a standalone @IgnoreEncodingDefault(CGPoint.zero) for this purpose. (I'm not certain what the best naming convention would be, I'd imagine you'd have better ideas.)

I feel this feature would be particularly useful for user-editable configuration files where we would want to omit any "optional" fields, or just keeping human-readable configurations minimal for git diffing.

soumyamahunt commented 5 months ago

@tatewake have you looked into the the HelperCoder functionality provided to implement what you want?

tatewake commented 5 months ago

Ah, I have not, I'll look into it.