我试图在self.setupDummyCards()完成将所有用户附加到self.cardViewModels.append(user.toCardViewModel())数组之后调用函数CardViewModels,但我不知道该把它放在哪里?

fileprivate func fetchUsersFromFirestore() {
    guard let uid = Auth.auth().currentUser?.uid else { return }


    Firestore.firestore().collection("Users").document(uid).collection("Following").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                let d = document.data()
                d.forEach({ (key: String, value: Any) in



                Database.firestorefetchUserForTinderCardWithUID(uid: key, completion: { (user) in

            self.cardViewModels.append(user.toCardViewModel())

//below it is called after each user is appended, meaning it appends the same users again and again until the last user is add
                   self.setupDummyCards()
                })
          //here is called before self.cardViewModels.append(user.toCardViewModel())
        })

        //here is called before self.cardViewModels.append(user.toCardViewModel())

    }
      //here is called before self.cardViewModels.append(user.toCardViewModel())
}
//here is called before self.cardViewModels.append(user.toCardViewModel())
    }
  //here is called before self.cardViewModels.append(user.toCardViewModel())
}

最佳答案

我刚得到documents.count,然后只调用self.setupDummyCards()一次,documents.count等于cardViewModels.count

   fileprivate func fetchUsersFromFirestore() {
    guard let uid = Auth.auth().currentUser?.uid else { return }
   Firestore.firestore().collection("Users").document(uid).collection("Following").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {

                let dc = querySnapshot?.documents.count

                for document in querySnapshot!.documents {
                let d = document.data()



                d.forEach({ (key: String, value: Any) in



                Database.firestorefetchUserForTinderCardWithUID(uid: key, completion: { (user) in

            self.cardViewModels.append(user.toCardViewModel())

                    if self.cardViewModels.count == dc {
                   self.setupDummyCards()
                    }
                })

        })



    }

}
    }

}

09-18 03:51