swift 如何只读取一次文件的数量?

cnwbcb6i  于 2023-08-02  发布在  Swift
关注(0)|答案(1)|浏览(122)

我正在尝试读取子集合中的文档数量,因为我使用下面的代码,但这是读取子集合中的文档数量的许多倍,我想确保只读取一次而不是多次的文档,请协助,谢谢

func getNumberOfComments() {
        Firestore.firestore().collection("posts").document(postId).collection("comments").getDocuments{ (snapshot, error) in
            if let error = error{
                print (error.localizedDescription)
            } else {
                if let snapshot = snapshot{
                    for document in snapshot.documents{
                        let data = document.data()

                        self.length = snapshot.count
                        print("counting " , self.length!)
                       // var length2 = data.count
                       // print ("printing ", length2)

                    }
                }
            }

        }
    }

字符串

7rfyedvj

7rfyedvj1#

这是阅读子集合中文档的两倍数量的文档
这是因为以下代码行:

self.length = snapshot.count
print("counting " , self.length!)

字符串
在每次迭代时调用。如果你只想被打印一次,那么只需在for循环开始之前将上面的代码行移出循环即可:

func getNumberOfComments() {
    Firestore.firestore().collection("posts").document(postId).collection("comments").getDocuments{ (snapshot, error) in
        if let error = error{
            print (error.localizedDescription)
        } else {
            if let snapshot = snapshot{
                self.length = snapshot.count
                print("counting " , self.length!)

                for document in snapshot.documents{
                    let data = document.data()
                }
            }
        }

    }
}

相关问题