swift - 字典用 .keys 改变索引位置——Swift
问题描述
我目前正在从 firebase 数据库中检索数据,并将数据存储在字典中。当我尝试像这样列出字典中的键时:snapDict?.keys
元素的索引与它们在数据库中的索引不同。
Database.database().reference().child("\(UserData().mySchool!)/posts").observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot.childrenCount)
let snapDict = snapshot.value as? [String: Any]
print(snapshot.value!)
let names = snapDict?.keys
print(names!)
for id in names! {
self.searchNames(id: id)
self.tableView.reloadData()
}
})
所以,你会认为当它们被放入字典时,它们会被打印为-LJRUC8n........-LOF6JUdm-onVuaq-zij
?
snapDict?.keys
印刷:
["-LOBSAv_l5_x1xnKwx3_", "-LJRUC8nPF3Vg-DDGiYQ", "-LOBLXpTs39yLZo6EnHl", "-LOF6JUdm-onVuaq-zij", "-LODhXPQi8G7MX1bSfeb", "-LJaUiEnGOcBjKsTWSCS", "-LOBLZzrLAlzkhoidnKf"]
我无法弄清楚这里的顺序/模式。按字母顺序?任何想法为什么订单会这样?
解决方案
根据定义,字典中的键是无序的。因此,当您将快照转换为字典时,有关节点顺序的任何信息都会丢失。
最重要的是,您在读取数据之前没有指定顺序。
要解决这两个问题:
Database.database().reference()
.child("\(UserData().mySchool!)/posts")
.queryOrderedByKey()
.observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot.childrenCount)
for child in snapshot.children.allObjects as! [FIRDataSnapshot] {
print(child.value)
}
})
推荐阅读
- https - 当我的检索权限类设置为 IsAuthenticated 时,为什么 DRF 在检索请求上返回 403?
- sql - 使用一列创建另一列
- oim - OIM 12c Rest api 启用/禁用用户
- javafx - 如何在按钮中添加图像?
- html - 如何避免内容在 100% 缩放时包装/重叠?
- javascript - Node.js 可读流事件“关闭”和“结束”之间的确切区别是什么?
- xsd - 在 XSD 中创建动态属性
- c++ - “Clang 中的 C++ 支持”页面中的 SVN 是什么意思?
- asp.net-mvc-viewmodel - MVC 视图中的 if else 条件
- python - 抓取不断更新的网页