【发布时间】:2022-01-01 18:43:59
【问题描述】:
我有一个 API 可以返回这样的有效负载(示例中只包含一项)。
{
"length": 1,
"maxPageLimit": 2500,
"totalRecords": 1,
"data": [
{
"date": "2021-05-28",
"peopleCount": 412
}
]
}
我知道我实际上可以创建一个类似的结构
struct Root: Decodable {
let data: [DailyCount]
}
struct DailyCount: Decodable {
let date: String
let peopleCount: Int
}
对于不同的调用,相同的 API 返回相同的根格式,但数据不同。此外,我不需要根信息(length、totalRecords、maxPageLimit)。
所以,我正在考虑在struct DailyCount 中创建一个自定义初始化,以便我可以在我的 URL 会话中使用它
let reports = try! JSONDecoder().decode([DailyCount].self, from: data!)
使用 Swift 5 我试过这个:
struct DailyCount: Decodable {
let date: String
let peopleCount: Int
}
extension DailyCount {
enum CodingKeys: String, CodingKey {
case data
enum DailyCountCodingKeys: String, CodingKey {
case date
case peopleCount
}
}
init(from decoder: Decoder) throws {
// This should let me access the `data` container
let container = try decoder.container(keyedBy: CodingKeys.self
peopleCount = try container.decode(Int.self, forKey: . peopleCount)
date = try container.decode(String.self, forKey: .date)
}
}
不幸的是,它不起作用。我遇到了两个问题:
- 该结构似乎不再符合
Decodable协议 -
CodingKeys不包含peopleCount(因此返回错误)
【问题讨论】: