gpt4 book ai didi

swift - 字典用 .keys 改变索引位置——Swift

转载 作者:行者123 更新时间:2023-11-28 10:06:25 24 4
gpt4 key购买 nike

我目前正在从 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()
}
})

这是在字典中的元素在数据库中的样子:enter image description here

因此,您会认为当将它们放入字典时,它们会打印为 -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)
}
})

关于swift - 字典用 .keys 改变索引位置——Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52693601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com