【问题标题】:Dictionary Changes Index Positions with .keys -- Swift字典用 .keys 改变索引位置——Swift
【发布时间】:2018-10-07 22:50:24
【问题描述】:

我目前正在从 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"]

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

【问题讨论】:

标签: swift dictionary firebase-realtime-database


【解决方案1】:

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

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

解决这两个问题:

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

【讨论】:

    猜你喜欢
    • 2015-11-24
    • 2015-10-24
    • 1970-01-01
    • 2021-11-09
    • 2022-10-26
    • 2013-09-23
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多