无法将类型“ [ViewController.MyStruct]”的值分配给类型“ [ViewController.MyOtherStruct]”

时间:2018-11-02 14:52:58

标签: ios json swift

我正在尝试解码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)
        }
    }

1 个答案:

答案 0 :(得分:1)

storyData的类型为[Doc],因此无法为其分配类型为[Response]的值。您需要访问docs的{​​{1}}属性,您可以通过在Response上调用flatMap来从响应数组中获取所有文档,并将结果展平以得到{可以将{1}}分配给response,而不是[Doc]

[[Doc]]