I'm using a property wrapper to decode the strings "true" and "false" as Booleans. I also want to make the key optional. So if the key is missing from the JSON, it should be decoded as nil. Unfortunately, adding the property wrapper breaks this and a Swift.DecodingError.keyNotFound
is thrown instead.
@propertyWrapper
struct SomeKindOfBool: Decodable {
var wrappedValue: Bool?
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let stringifiedValue = try? container.decode(String.self) {
switch stringifiedValue.lowercased() {
case "false": wrappedValue = false
case "true": wrappedValue = true
default: wrappedValue = nil
}
} else {
wrappedValue = try? container.decode(Bool.self)
}
}
}
public struct MyType: Decodable {
@SomeKindOfBool var someKey: Bool?
}
let jsonData = """
[
{ "someKey": true },
{ "someKey": "false" },
{}
]
""".data(using: .utf8)!
let decodedJSON = try! JSONDecoder().decode([MyType].self, from: jsonData)
for decodedType in decodedJSON {
print(decodedType.someKey ?? "nil")
}
Any idea how to resolve this?
{}
, which I am not sure what it's supposed to be? And next time you post an error message then post the full message. – SissondecodeIfPresent
instead? – Engrossing{}
. It should setsomeKey
to nil since it's an Optional. – Especially