我正在尝试解码some JSON,但我不断收到错误消息:
Cannot assign value of type '[ViewController.Response]' to type '[ViewController.Doc]'
据我所见,两个结构都以相同的方式设置,所以我对这里的问题感到困惑。
这些是我的结构:
struct Status: Decodable {
let status: String
let response: [Response]
}
struct Response: Decodable {
let docs: [Doc]
}
struct Doc: Decodable {
let webUrl: String
let abstract: String
enum CodingKeys: String, CodingKey {
case webUrl = "web_url"
case abstract
}
init(from decoder:Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
abstract = try container.decode(String.self, forKey: .abstract)
webUrl = try container.decode(String.self, forKey: .webUrl)
}
}
当我在fetchData
中调用viewDidLoad
函数时引发错误(在.success
的{{1}}情况下出错):
object.response
编辑:这是我用JSON数据填充的数组:
fetchData(url: jsonUrl) { (result: FetchResult<Status>) in
switch result {
case .success(let object): self.storyData = object.response
print("Results \n\n\n\n \(object.response)")
case .failure(let error): print(error)
}
}
答案 0 :(得分:1)
storyData
的类型为[Doc]
,因此无法为其分配类型为[Response]
的值。您需要访问docs
的{{1}}属性,您可以通过在Response
上调用flatMap
来从响应数组中获取所有文档,并将结果展平以得到{可以将{1}}分配给response
,而不是[Doc]
。
[[Doc]]