如何计算 swift 中来自 firestore 查询的文档?

How can I count the documents from a firestore query in swift?

答案一定是在盯着我看,但我看不到。我正在尝试查询 firestore 并获取它标识的文档数量,以便我可以将其输入到我的 TableView(行数)函数中。计数器以某种方式在 for 循环内工作,我希望该变量保持该增加的值,但当我将它传回时它会恢复为零。这是范围问题吗?我错过了什么?这是我的代码:

func runQueryForNumberOfGames() -> Int {
    var counter = 0
    // query the games for the user who is logged into app
    let currentUid = Auth.auth().currentUser!.uid

    db.collection("games").whereField("userTrackingGame", isEqualTo: currentUid).getDocuments { (querySnapshot, err) in
               if let err = err {
                print("error getting documents: \(err)")
                return
               }
               else {

                    for document
                        in querySnapshot!.documents {
                        print(document)
                        counter += 1
                        print("the counter is: \(counter)")
                    }
                }

    }
    print("the counter outside of the for loop is \(counter)")
    return (counter)
}

它的异步函数所以你需要 return 完成处理程序

func runQueryForNumberOfGames(completion: @escaping (Int?)-> Void) {
    var counter = 0
    // query the games for the user who is logged into app
    let currentUid = Auth.auth().currentUser!.uid

    db.collection("games").whereField("userTrackingGame", isEqualTo: currentUid).getDocuments { (querySnapshot, err) in
               if let err = err {
                print("error getting documents: \(err)")
                completion(nil)
                return
               }
               else {

                    for document
                        in querySnapshot!.documents {
                        print(document)
                        counter += 1
                        print("the counter is: \(counter)")
                    }

                completion(counter)
                }

    }

}

如何使用

runQueryForNumberOfGames {[weak self] (counter) in
    if let count = counter  {
        print(count)
    }
}