我对如何实现这一点感到困惑。我正在尝试通过网络调用循环遍历并相加Double值的运行总和。我读过的所有内容都建议使用DispatchGroup。我的完成要么过早地调用,要么根本不被调用,我已经尝试了我能想到的所有.enter、.leave和.wait的配置。
let group = DispatchGroup()
var runningTotal: Double = 0.00
ref.observeSingleEvent(of: .value) { (snapshot) in
guard let bills = snapshot.value as? [String: AnyObject] else {
//error
return
}
for billId in bills.keys {
group.enter()
print("Entering")
Database.database().reference().child("bills").child(billId).observeSingleEvent(of: .value, with: { (snapshot) in
guard let bill = snapshot.value as? [String: AnyObject] else {
return
}
if let amount = bill["amount"] as? Double {
runningTotal += amount
}
group.leave()
print("Leaving")
})
}
completion(runningTotal)
}
group.wait()
}