首页 > 解决方案 > 字典用 .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"]

我无法弄清楚这里的顺序/模式。按字母顺序?任何想法为什么订单会这样?

标签: swiftdictionaryfirebase-realtime-database

解决方案


根据定义,字典中的键是无序的。因此,当您将快照转换为字典时,有关节点顺序的任何信息都会丢失。

最重要的是,您在读取数据之前没有指定顺序。

要解决这两个问题:

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)     
      }
  })

推荐阅读