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

Feature: Decode logical Bool into a real Bool #50

Open
Andy0570 opened this issue Apr 27, 2022 · 1 comment
Open

Feature: Decode logical Bool into a real Bool #50

Andy0570 opened this issue Apr 27, 2022 · 1 comment

Comments

@Andy0570
Copy link

I've added a Bool type auto-conversion function, so if people want to add it to their projects, I'll try pulling requests.

JSON Swift
"false", "no", "0", "n", "f", 0, false false
"true", "yes", "1", "y", "t", 1, true true
import Foundation

@propertyWrapper
public struct BoolValue: Codable {
    public var wrappedValue: Bool

    public init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let stringifiedValue = try? container.decode(String.self) {
            switch stringifiedValue.lowercased() {
            case "false", "no", "0", "n", "f": wrappedValue = false
            case "true", "yes", "1", "y", "t": wrappedValue = true
            default:
                let description = "Expected to decode Bool but found a '\(stringifiedValue)' instead."
                throw DecodingError.dataCorruptedError(in: container, debugDescription: description)
            }
        } else if let integerifiedValue = try? container.decode(Int.self) {
            switch integerifiedValue {
            case 0: wrappedValue = false
            case 1: wrappedValue = true
            default:
                let description = "Expected to decode Bool but found a '\(integerifiedValue)' instead."
                throw DecodingError.dataCorruptedError(in: container, debugDescription: description)
            }
        } else {
            wrappedValue = try container.decode(Bool.self)
        }
    }

    public func encode(to encoder: Encoder) throws {
        try wrappedValue.encode(to: encoder)
    }
}

Usage:

@BoolValue var isFollow: Bool
@marksands
Copy link
Owner

We already have @LosslessBoolValue. I could add the logical strings as an additional decodable step. How does that sound? WIP here

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