列表视图 SwiftUI 的字典数组

Mdo*_*le1 4 dictionary swiftui

我有一组字典,我想用 SwiftUI 填充到列表视图中。

我过去使用过 for 循环,但由于在 View 中这是不可能的,所以我不知道该怎么做。我可以使用下面的代码实现部分结果。

struct Test : View {
let dict = csvArray[0]

var body: some View {
    let keys = dict.map{$0.key}
    let values = dict.map {$0.value}

    return List {

        ForEach(keys.indices) {index in
            HStack {
                Text(keys[index])
                Text("\(values[index])")
            }
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)

我希望索引整个字典数组并将它们附加到列表中,而不仅仅是 csvArray[0]。

Moj*_*ini 6

这就像关键值的部分,对吗?

所以这样做:

这是一个示例csvArray,这可以是任何内容,但您应该根据原始数据类型更新其余代码

let csvArray = [
    [ "section0-key0": "section0-value0",
      "section0-key1": "section0-value1"],

    [ "section1-key0": "section1-value0",
      "section1-key1": "section1-value1"],

    [ "section2-key0": "section2-value0",
      "section2-key1": "section2-value1"]
]
Run Code Online (Sandbox Code Playgroud)

这是单个字典的代码。但这将使用该字典而不是硬编码的字典:

struct SectionView : View {
    @State var dict = [String: String]()

    var body: some View {
        let keys = dict.map{$0.key}
        let values = dict.map {$0.value}

        return  ForEach(keys.indices) {index in
            HStack {
                Text(keys[index])
                Text("\(values[index])")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是连接到原始数组的列表构建器。我使用部分来表示数据结构的意义。

struct ContentView: View {
    var body: some View {
        List {
            ForEach(csvArray, id:\.self) { dict in
                Section {
                    SectionView(dict: dict)
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,您不能按照字典中键值的顺序进行中继。所以我建议你sort在填充列表之前做一些ing 或使用另一种数据结构,比如classstruct代替普通字典。