BetterCodable icon indicating copy to clipboard operation
BetterCodable copied to clipboard

Feature: Decode logical `Bool` into a real `Bool`

Open Andy0570 opened this issue 3 years ago • 1 comments

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

Andy0570 avatar Apr 27 '22 12:04 Andy0570

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

marksands avatar Sep 09 '22 05:09 marksands