Swift Codable手动解码可选变量
问题描述:
我有以下代码:
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
函数时,它可以正常工作。错误为没有与键龄(\ age\)相关的值。
。
Problem is it's crashing on age = try values.decode(String.self, forKey: .age)
. When I take that init
function out it works fine. The error is No value associated with key age (\"age\").
.
任何想法关于如何使该可选对象不存在时崩溃?出于其他原因,我还需要 init
函数,但仅举了一个简单的示例来说明发生了什么。
Any ideas on how to make that optional and not have it crash when it doesn't exist? I also need that init
function for other reasons, but just made a simple example to explain what is going on.
答
年龄是可选的:
let age: String?
因此,尝试以这种方式进行解码:
So try to decode in this way:
let age: String? = try values.decodeIfPresent(String.self, forKey: .age)