我在循环访问导航列表中的 API 调用解码的 JSON 数据时遇到问题。我已成功将数据放入变量中,但似乎无法弄清楚如何在导航视图中循环数据和列表。我收到的错误是:“通用结构‘ForEach’要求‘CompetitionGroup’符合‘RandomAccessCollection’”
struct ContentView: View {
let compse = competitionslist
var body: some View {
NavigationView {
List {
//ERROR ForEach(compse!) { competition in
NavigationLink(destination: Text(competition.genericname)) {
Image(systemName: "airplane")
Text(competition.genericname)
}.padding()
}
.navigationTitle("Destinations")
}
}
}
}
数据解码如下:
func getComps() -> CompetitionGroup? {
let headers = [
"x-rapidapi-key": "apices",
"x-rapidapi-host": "api.webnsite"
]
let request = NSMutableURLRequest(url: NSURL(string: "https://football-web-pages1.p.rapidapi.com/competitions.json?include=rounds")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error as Any)
} else {
let httpResponse = response as? HTTPURLResponse
do {
let decoder = JSONDecoder()
let comps = try decoder.decode(CompetitionGroup.self, from: data!)
self.competitions = comps
}
catch {
print("Error in JSON")
}
}
})
dataTask.resume()
return competitions
}
CompetitionGroup模型保存了Competitions模型的列表,两个模型的结构如下所示。任何帮助将不胜感激。
public struct CompetitionGroup: Codable {
var competitions:[Competition]?
}
public struct Competition: Codable {
var id: Int?
var type: String?
var genericname: String?
var fullname: String?
enum CodingKeys: String, CodingKey {
case genericname = "generic-name"
case fullname = "full-name"
}
}
您需要先解开这些值
var body: some View {
NavigationView {
let competitions = compse?.competitions ?? []
List {
ForEach(competitions, id: \.id) { competition in
NavigationLink(destination: Text(competition.genericname ?? "")) {
Image(systemName: "airplane")
Text(competition.genericname ?? "")
}.padding()
}
.navigationTitle("Destinations")
}
}
}
注意