如何使用[String:generic struct]与Json列出

时间:2019-12-01 16:20:49

标签: sections swiftui-list

我有这个结构:

// 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
}

,我想使用这些结构在SwiftUI中创建数据列表。我尝试过:

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()
    }
}

但是我遇到了这个错误:

Initializer 'init(_:rowContent:)' requires that 'Dictionary<String, APIData>.Values' conform to 'RandomAccessCollection'

如何为keys的列表valuesAPIData修复它?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:(但请记住:如果您遍历字典,则顺序是随机的。。。)

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`
    }