Swift 4添加了新Codable
协议。当我使用JSONDecoder
它时,它似乎要求类的所有非可选属性Codable
在JSON中具有键,否则会引发错误。
使类的每个属性为可选似乎是不必要的麻烦,因为我真正想要的是使用json中的值或默认值。(我不希望该属性为零。)
有没有办法做到这一点?
class MyCodable: Codable {
var name: String = "Default Appleseed"
}
func load(input: String) {
do {
if let data = input.data(using: .utf8) {
let result = try JSONDecoder().decode(MyCodable.self, from: data)
print("name: \(result.name)")
}
} catch {
print("error: \(error)")
// `Error message: "Key not found when expecting non-optional type
// String for coding key \"name\""`
}
}
let goodInput = "{\"name\": \"Jonny Appleseed\" }"
let badInput = "{}"
load(input: goodInput) // works, `name` is Jonny Applessed
load(input: badInput) // breaks, `name` required since property is non-optional