ios - 在 SwiftUI 中为数据字典发出读取值
问题描述
我有以下字典:
let selection: [String: [String : Bool]]
我可以这样显示数据:
ForEach(selection.keys.sorted(), id: \.self) { item in
Text("\(item.description)")
.font(.caption)
.fontWeight(.bold)
}
以上正确打印了字典的键。
我遇到的问题是如何访问字典的值(或剩余部分 [String : Bool])?
解决方案
您选择的方法可能取决于您的意图。以下是访问[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")")
}
}
}
推荐阅读
- jq - 如何将函数应用于jq中的多个字段
- reactjs - 按 Escape 关闭 Material UI 工具提示
- python - 将 DataFrame 作为新列附加
- javascript - Reactjs 如何从 Azure 存储容器下载文件
- excel - 基于矩阵隐藏/取消隐藏Excel工作表
- node.js - 我正在尝试为 node.js 创建一个登录页面,但在访问数据库中保存的数据时遇到问题
- php - Laravel websocket 与 vue.js 实时聊天
- java - Jenkins 权限被拒绝 /usr/share/maven 无法构建测试
- python - Mac用brew安装python3.6
- java - 如何模拟系统环境