我在将我的 JSON 显示到我的内容视图中时遇到了问题。我可以解码数据并将其保存到我打印和查看的字典中。但是,当它使用 ForEach 在 ContentView 中显示它时。我收到此错误无法将类型“[String : String]”的值转换为预期的参数类型“Binding”下面是我的 ContentView、Struct 和 ApiCall 的代码。我已经阅读了有关 stackoverflow 的其他解决方案并尝试了它们,但它们不起作用。
struct ContentView: View {
@StateObject var api = APICALL()
var body: some View {
let country = api.storedData.countries
VStack(alignment: .leading) {
ForEach(country.id, id: \.self) { country in
HStack(alignment: .top) {
Text("\(country.countries)")
}
}
.onAppear {
api.loadData()
}
}
}
}
我的 ApiCall 类加载数据,以及结构。
// MARK: - Country
struct Country: Codable, Identifiable {
let id = UUID()
var countries: [String: String]
enum CodingKeys: String, CodingKey {
case countries = "countries"
}
}
class APICALL: ObservableObject {
@Published var storedData = Country(countries: [:])
func loadData() {
let apikey = ""
guard let url = URL(string:"https://countries-cities.p.rapidapi.com/location/country/list?rapidapi-key=\(apikey)") else {
print("Your Api end point is Invalid")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let response = try? JSONDecoder().decode(Country.self, from: data) {
DispatchQueue.main.async {
self.storedData.countries = response.countries
print(self.storedData.countries)
}
return
}
}
}
.resume()
}
}
任何朝着正确方向的点都是绝对有帮助的。