Swift 4 では、新しいCodable
プロトコルが追加されました。私が使用JSONDecoder
すると、クラスのオプションではないすべてのプロパティがCodable
JSON にキーを持つ必要があるように見えます。そうしないと、エラーがスローされます。
クラスのすべてのプロパティをオプションにすることは、本当に必要なのはjsonの値またはデフォルト値を使用することであるため、不必要な面倒のように思えます。(プロパティをnilにしたくありません。)
これを行う方法はありますか?
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