首页 > 解决方案 > 在 SwiftUI 中为数据字典发出读取值

问题描述

我有以下字典:

let selection: [String: [String : Bool]]

我可以这样显示数据:

ForEach(selection.keys.sorted(), id: \.self) {  item in

    Text("\(item.description)")
        .font(.caption)
        .fontWeight(.bold)

}

以上正确打印了字典的键。

我遇到的问题是如何访问字典的值(或剩余部分 [String : Bool])?

标签: iosswiftswiftui

解决方案


您选择的方法可能取决于您的意图。以下是访问[String: Bool]数据的几种方法。这个例子非常做作,因为它是一堆不同的方法粘在一起,但它应该给你一些关于访问数据的方法的想法。

struct ContentView : View {
    
    let selection: [String: [String : Bool]] = [:]

    var body: some View {
        ForEach(selection.keys.sorted(), id: \.self) {  key in
            Text("\(key)")
                .font(.caption)
                .fontWeight(.bold)
            
            let item = selection[key]! //get the [String: Bool] dictionary item
            ForEach(item.keys.sorted(), id: \.self) { secondaryKey in
                Text("\(secondaryKey)")
                Text("\((item[secondaryKey] ?? false) ? "true" : "false")")
            }
        }
        
        ForEach(selection.map { ($0,$1) }, id: \.0) { (key, value) in
            Text(key)
            ForEach(value.keys.sorted(), id: \.self) { secondaryKey in
                Text("\(secondaryKey)")
            }
            Text("MyKey = \((value["myKey"] ?? false) ? "true" : "false")")
        }
    }
}

推荐阅读