我正在使用属性包装器将字符串“true”和“false”解码为布尔值。我还想让密钥成为可选的。因此,如果 JSON 中缺少密钥,则应将其解码为 nil。不幸的是,添加属性包装器会破坏这一点,Swift.DecodingError.keyNotFound
而是抛出 a 。
@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")
}
知道如何解决这个问题吗?