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

@DefaultFalse cannot deal string number #44

Open
chunxige opened this issue Sep 2, 2021 · 2 comments
Open

@DefaultFalse cannot deal string number #44

chunxige opened this issue Sep 2, 2021 · 2 comments

Comments

@chunxige
Copy link

chunxige commented Sep 2, 2021

let data = """
    {"a": "1"}
    """.data(using: .utf8)!

struct A: Decodable {
    @DefaultFalse var a: Bool
}

let m = try JSONDecoder.init().decode(A.self, from: data)

print(m.a)  // print is false

but actual true is right answer

@serjooo
Copy link
Contributor

serjooo commented Sep 2, 2021

Hey chunxige,

In this case of yours you might want to use @LosslessValue instead of @DefaultFalse as the type of the response doesn't match the type that you expect and you would like it not fail if possible in decoding.

However, even with @LosslessValue this will not work since this was an edge case that we thought it might not make sense for us to cover. I would recommend in this case to create your own small property wrapper for this for the time being if your backend response can't be improved or is out of your control.

It can look something as simple as this:

@propertyWrapper
struct DefaultFalseString: Decodable {

    let wrappedValue: Bool

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let string = try? container.decode(String.self) {
            wrappedValue = string == "1" ? true : false
        } else if let bool = try? container.decode(Bool.self) {
            wrappedValue = bool
        } else {
            wrappedValue = false
        }
        // You can add int support as well 
    }
}

Or you can try to have your own version of @LosslessValue that supports this behavior and use it in your project as well.

I hope this helps get rid of your problem.

@marksands
Copy link
Owner

WIP... thoughts welcome. I'm considering merging this though.

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

3 participants