I have this struct, :
// MARK: - JsonAPIData
struct JsonAPIData: Codable {
let data: [String: APIData]
let success: Bool
}
// MARK: - Datum
struct APIData: Codable, Identifiable {
let id = UUID()
let maxVersion, minVersion: Int
}
and I want to use these Structures to create a list of data in SwiftUI. I tried this:
struct ContentView: View {
@State var results: JsonAPIData
var body: some View {
List(results.data.values) { data in
Text("\(data)")
}
.onAppear {
self.loadData()
}
}
func loadData() {
//My code to load `results`
}.resume()
}
}
but I had this error:
Initializer 'init(_:rowContent:)' requires that 'Dictionary<String, APIData>.Values' conform to 'RandomAccessCollection'
How can I fix it for list keys
and values
of APIData
?
you can try this: (but keep in mind: if you loop over dictionaries the order is random....)
struct JsonAPIData: Codable {
let data: [String: APIData]
let success: Bool
}
// MARK: - Datum
struct APIData: Codable, Identifiable {
let id = UUID()
let maxVersion, minVersion: Int
}
struct ContentView: View {
func getKeys() -> [String] {
return results.data.map{$0.key}
}
func getValues() -> [APIData] {
return results.data.map{$0.value}
}
@State var results: JsonAPIData
var body: some View {
List(getKeys(), id: \.self) { key in
Text("\(self.results.data[key]!.maxVersion)")
}
.onAppear {
self.loadData()
}
}
func loadData() {
//My code to load `results`
}