我收到一个严重错误,说明如下。我已经尝试了所有方法,但我似乎无法访问 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/