Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decoding empty JSON string value into nil with Codable #19

Closed
WingCH opened this issue Aug 5, 2021 · 2 comments
Closed

Decoding empty JSON string value into nil with Codable #19

WingCH opened this issue Aug 5, 2021 · 2 comments

Comments

@WingCH
Copy link

WingCH commented Aug 5, 2021

normal case:

{
    "maintenance": true
}

{
    "maintenance": false
}

If there is no maintenance station then it will become empty string

{
    "maintenance": ""
}

i want to have nil if maintenance is empty string in json

struct Demo: Codable {
    var maintenance: Bool?
}

Is there a good way to do it?

@GottaGetSwifty
Copy link
Owner

I think something like this should work, no testing done though:

struct NilBoolFallback: FallbackValueProvider {
    public static var defaultValue: Bool? { nil }
}

@FallbackDecoding<NilBoolFallback>
var maintenance: Bool?

The idea being if it's anything other than a Bool (and thus fails to decode) it will use the defaultValue

@GottaGetSwifty
Copy link
Owner

@WingCH Re-open if you have any more questions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants