ios - Swift decodable 无法访问数组中的嵌套数据

标签 ios json swift decodable

我收到一个严重错误,说明如下。我已经尝试了所有方法,但我似乎无法访问 Movie 结构,因为它说父“Type”没有名为“data”的成员,尽管它显然有。

"Value of type '[Type?]' has no member 'data'"

型号

struct SearchData: Decodable  {
     let data: [Type?]
}

struct Type: Decodable  {
     let data: [Movie?]
}

struct Movie: Decodable {
     let title: String?
}

Controller

    fileprivate var searchResults = [Movie?]()

    func fetchTitles()  {
    let urlString = "https://www.what-song.com/api/search?limit=10&field=america"
    guard let url = URL(string: urlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, err) in
        // if error occurs
        if let err = err    {
            print("Failed to fetch titles", err)
            return
        }
        // if success

        guard let data = data else { return }

        do {
            let searchResult =  try JSONDecoder().decode(SearchData.self, from: data)

            self.searchResults = searchResult.data.data

            print(searchResult)

        }   catch   {
            print("Failed to decode JSON:", error)
        }
    }.resume()
}

最佳答案

试试这个:

var movieTitles = [String]()

for type in searchResult.data {
   for movie in type.data {
       guard let title = movie.title else { return }
       print(title)
       movieTitles.append(title)
   }
}

关于ios - Swift decodable 无法访问数组中的嵌套数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54798590/

相关文章:

ios - 如何检查 Objective-C 中的有效对象?

ios - 测距信标间隔

python - 将 cURL 转换为 Python 请求错误

SwiftUI 条件列表 - 无法推断复杂的闭包返回类型

ios - 在 swiftui 中使用类

ios - 为什么这不会崩溃?

iOS9 UIWebView/Chrome CSS 过渡

php - 解析文本文档的最佳方式

c++ - 使用 boost 读取复杂的 JSON 数组

ios - 查询 NearGeoPoint 返回空对象