【问题标题】:How to create a dictionary based on Firebase, but values being defined are the children and the values that are defining are parent nodes [Swift]如何基于 Firebase 创建字典,但定义的值是子节点,而定义的值是父节点 [Swift]
【发布时间】:2023-12-26 03:23:01
【问题描述】:

我需要生成一个格式为 [States: Representatives] 的字典。我已经存储了一个代表列表,其中包含有关该代表的几位相关信息。它看起来像这样:

我需要根据他们在其中的状态值对这些代表进行排序。

我尝试隔离每个状态值,但最终只打印出整个子快照。

ref = Database.database().reference(fromURL: "Redacted for Privacy")
    ref.observeSingleEvent(of: .value, with: { snapshot in
        print(snapshot.childrenCount) // I got the expected number of items
        let enumerator = snapshot.children
        while let rest = enumerator.nextObject() as? DataSnapshot {
            print(rest.value!)
        }
    })

我怎样才能存储每个代表,以便它们实际上是由它们的状态定义的?例如,字典中的一个条目可能是 ALABAMA:[Jo Bonner, Martha Roby, Mike Rogers, Robert B Aderholt, Mo *s, Spencer Bachus, Terri A Sewell]。我发现的所有示例似乎都无法更改为执行此操作。

我尝试使用此代码:

        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(6), execute: {
        print("six second delay")
        print("entered function")
        var i: Int = 0
        var x: Int = 0
        while(i < self.repList.count){
            print("i = " + String(i))
            self.ref = Database.database().reference(fromURL: "Redacted for privacy" + "/" + self.repList[i] + "/" + "State")
            self.ref.observeSingleEvent(of: .value, with: { snapshot in
                print(snapshot.value!)
                let valString = snapshot.value! as? String
                if (valString != nil){
                    self.captured = String(valString!)
                    print("Noice")

                }
                else {
                    print("ya done f***** up")
                }
            })
            while(x < self.stateCongmanDict.count){
                print("x = " + String(x))
                if (self.stateCongmanDict[self.captured] != nil){
                    self.alreadyThere = true
                    break
                }
                x = x + 1
            }
            self.stateCongmanDict[self.captured] = [self.captured]
            i = i + 1
        }
        i = 0
        x = 0
        while (i < self.repList.count){
            print("i restarted = " + String(i))
            self.ref = Database.database().reference(fromURL: "Redacted for privacy" + "/" + self.repList[i] + "/" + "State")
            self.ref.observeSingleEvent(of: .value, with: { snapshot in
                print(snapshot.value!)
                let valString = snapshot.value! as? String
                if (valString != nil){
                    self.captured = String(valString!)
                    print("Noice")

                }
                else {
                    print("ya done f***** up")
                }
            })
            while(x < self.stateCongmanDict.count){
                print("restarted x = " + String(x))
                if (self.stateCongmanDict[self.captured]! != [""]){
                    self.alreadyThere = true
                    break
                }
                else {
                    var c: Int = 0
                    var capturedDos: String = ""
                    while (c < self.repList.count - 1){
                        print("c = " + String(c))
                        self.ref = Database.database().reference(fromURL: "Redacted for privacy" + "/" + self.repList[c] + "/" + "State")
                        self.ref.observeSingleEvent(of: .value, with: { snapshot in
                            print(snapshot.value!)
                            let valString = snapshot.value! as? String
                            if (valString != nil){
                                capturedDos = String(valString!)
                                print("Noice")
                            }
                            else {
                                print("ya done f***** up")
                            }
                        })
                        if (capturedDos == self.captured){
                            print("DO YOU SEE ME!!!!")
                            self.stateCongmanDict[capturedDos]?.append(self.repList[i])
                        }
                        c = c + 1
                    }
                }
                x = x + 1
            }
            i = i + 1
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(6), execute: {
            print("six second delay check state")
            print("succeed if seen:" + String(describing: self.stateCongmanDict))
        })
    })

不幸的是,它只打印一个空字典:

六秒延迟检查状态 如果看到成功: [“”:[“”,“”,“”,“”,“”,“”,“”,“”,“”,“”,“”,“”,“”,“”,“”, “”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“” , "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " "、""、""、""、""、""、""、""、""、""、""、""、""、""、""、""、""、 “”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“” , "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " "、""、""、""、""、""、""、""、""、""、""、""、""、""、""、""、""、 “”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“” , "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " "、""、""、""、""、""、""、""、""、""、""、""、""、""、""、""、""、 “”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“” , "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " "、""、""、""、""、""、""、""、""、""、""、""、""、""、""、""、""、 “”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“” , "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " " , "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " "、""、""、""、""、""、""、""、""、""、""、""、""、""、""、""、""、 “”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“” , "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " "、""、""、""、""、""、""、""、""、""、""、""、""、""、""、""、""、 “”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“” , "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " “、”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、 “”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“” , "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " “、”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、 “”、“”、“”、“”、“”、“”、“”、“”]]

【问题讨论】:

  • 你能告诉我这条语句的输出是什么:print(rest.value!) 吗?
  • 如果我没记错的话,它只是打印出了一个名字下的所有孩子(比如“Aaron Schock”)

标签: swift firebase dictionary firebase-realtime-database


【解决方案1】:

我认为你需要遍历孩子,然后检查字典中是否已经存在状态,所以我认为你可以做这样的事情(我没有测试过,但想法是一样的):

var dictionary = [String: [String]]()
ref.observeSingleEvent(of: .value, with: { snapshot in
        print(snapshot.childrenCount) // I got the expected number of items
        let enumerator = snapshot.children
        while let rest = enumerator.nextObject() as? DataSnapshot {
            print(rest.value!)
            let name = rest.key
            if let value = rest.value as? [String: Any] {
                  let state = value["State"] as? String
                  if var repsArr = self.dictionary[state] as? [String] {
                          repsArr.append(name)
                          self.dictionary[state] = repsArr
                  }else {
                          let newRepsArr = [name]
                          self.dictionary[state] = newRepsArr
                  }
                  print("Dictionary Inside while loop: \(self.dictionary)") //watch dictionary build itself
            }

        }
        print("Dictionary: \(self.dictionary)")
    })

【讨论】:

  • 它不会打印完整的字典(我认为),因为我只得到一个存储在数组部分(值)中的值
  • 我添加了 6 秒延迟
  • @PGODULTIMATE 如果您只使用上面的代码而不添加六秒延迟,那么输出是什么?
  • 是一样的——我刚查过
  • @PGODULTIMATE 好的,您能告诉我while 循环的运行次数与您的firebase 数据库中的代表数量相同,即print(rest.value!) 打印所有代表吗?