Open
Description
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
Metadata
Metadata
Assignees
Labels
No labels