我收到一个严重错误,陈述以下内容。我已经尝试了所有方法,但似乎无法访问Movie结构,因为它说父“ Type”没有名为“ data”的成员,即使它显然也是如此。
“类型'[Type?]'的值没有成员'数据'“
模型
struct SearchData: Decodable {
let data: [Type?]
}
struct Type: Decodable {
let data: [Movie?]
}
struct Movie: Decodable {
let title: String?
}
控制器
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()
}
答案 0 :(得分:1)
尝试一下:
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)
}
}
答案 1 :(得分:1)
我认为您在这里犯了一个小错误
searchResult.data
将返回一个
数组类型
您还需要解析该数组,像这样
searchResults = (searchResult.data[0]?.data)!