我有以下代码:
import Foundation
let jsonData = """
[
{"firstname": "Tom", "lastname": "Smith", "age": "28"},
{"firstname": "Bob", "lastname": "Smith"}
]
""".data(using: .utf8)!
struct Person: Codable {
let firstName, lastName: String
let age: String?
enum CodingKeys : String, CodingKey {
case firstName = "firstname"
case lastName = "lastname"
case age
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
firstName = try values.decode(String.self, forKey: .firstName)
lastName = try values.decode(String.self, forKey: .lastName)
age = try values.decode(String.self, forKey: .age)
}
}
let decoded = try JSONDecoder().decode([Person].self, from: jsonData)
print(decoded)
问题是它正在崩溃age = try values.decode(String.self, forKey: .age)
。当我取出该init
功能时,它工作正常。错误是No value associated with key age (\"age\").
。
关于如何使它成为可选并且在它不存在时不让它崩溃的任何想法?由于其他原因,我还需要该init
功能,但只是做了一个简单的例子来解释发生了什么。