如何统计Firebase数据库中所有客户的“Open service”状态数量?
问题描述
你的数据库结构为userDatabase/userID/Customers,包含两位客户,路径示例如下:
usersDatabase g8voYf1yoChnpmhkoPgtmO4FQT62 - (uid) Customers Tom Smith (customer with custom ID) -LDFZw1tca8KOrnqyyWH - (auto id of customer child) Status of Service: "Open service" Ben Thomas (customer with custom ID) -LDFZw1tca8KOjgoenBN - (auto id of customer child) Status of Service: "Open service"
你希望统计数据库中状态为Open service的客户总数,但目前仅能逐个打印状态值。现有取值代码如下:
let userID = Auth.auth().currentUser?.uid let usersDatabaseRef = Database.database().reference().child("usersDatabase").child(userID!).child("Customers") usersDatabaseRef.observe(.value, with: { snapshot in var totalCustomerCount = 0 for child in snapshot.children { let childSnap = child as! DataSnapshot let childrenRef = childSnap totalCustomerCount += Int(childrenRef.childrenCount) print("user \(childSnap.key) has \(childrenRef.childrenCount) customers") let userCustomerSnap = childSnap for customer in userCustomerSnap.children.allObjects as! [DataSnapshot] { let customerSnap = customer let dict = customerSnap.value as! [String: Any] let stat = dict["Status of Service"] as! String let myStatistic = PrintModel(status: stat) self.statistic.append(myStatistic) print("Statistic: \(String(describing: myStatistic.status))") } } print("... and there are \(totalCustomerCount) total customers") })
当前日志输出:
- user Tom Smith has 1 customers
- Statistic: Optional("Open service")
- user Ben Thomas has 1 customers
- Statistic: Optional("Open service")
你期望的输出为:
- Statistic: 2
解决方案
很容易实现这个统计需求,我们只需要新增一个专门的计数器,遍历客户时判断状态并累加即可。修改后的代码如下:
let userID = Auth.auth().currentUser?.uid let usersDatabaseRef = Database.database().reference().child("usersDatabase").child(userID!).child("Customers") usersDatabaseRef.observe(.value, with: { snapshot in // 初始化计数器,专门统计"Open service"的数量 var openServiceCount = 0 for child in snapshot.children { let childSnap = child as! DataSnapshot for customer in childSnap.children.allObjects as! [DataSnapshot] { let dict = customer.value as! [String: Any] // 用可选绑定避免强制解包导致崩溃 if let stat = dict["Status of Service"] as? String { if stat == "Open service" { openServiceCount += 1 } // 若仍需保存所有状态记录,保留这部分代码 let myStatistic = PrintModel(status: stat) self.statistic.append(myStatistic) } } } // 打印最终统计结果 print("Statistic: \(openServiceCount)") })
关键改动说明:
- 新增
openServiceCount变量,初始值为0,专门用于统计符合条件的状态数量 - 对状态值使用可选绑定
if let stat = ...,避免强制解包引发崩溃 - 遍历每个客户时,判断状态是否等于
Open service,符合条件则计数器加1 - 移除了不需要的总客户数统计代码(若需要可保留),最后直接输出统计好的结果
运行修改后的代码,就能得到你想要的Statistic: 2输出啦。
内容的提问来源于stack exchange,提问作者Krzysztof Łowiec
相关产品推荐
相关产品推荐

