Skip to content

Feature: Decode logical Bool into a real Bool #50

Description

@Andy0570

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions