【问题标题】:How can I count the documents from a firestore query in swift?如何快速计算来自 Firestore 查询的文档?
【发布时间】:2023-03-30 17:45:01
【问题描述】:

答案一定是盯着我看,但我看不到。我正在尝试查询 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)
}

【问题讨论】:

    标签: ios arrays swift firebase scope


    【解决方案1】:

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

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

    【讨论】:

    • 阿里,这很有帮助,因为我不知道这一点。我仍在努力提取计数器以将其传递给变量(在函数调用之外)。您能否扩展答案的 部分?好像如果我尝试在 func 调用之外使用 count 它不会被视为定义的常量。
    • runQueryForNumberOfGames {[weak self] (counter) in if let count = counter { print(count) } } count 是你想要的计数器...尝试运行这段代码'
    • 并没有完全解决我的问题,但加深了我的理解。感谢您抽出时间阿里!
    猜你喜欢
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 2023-02-02
    • 2017-08-18
    • 1970-01-01
    • 2019-04-14
    • 2018-07-17
    相关资源
    最近更新 更多