0

I've written a method which returns the result of a firestore DB read through a closure. Throughout my app I want to call this method several times with two optional Boolean parameters passed on. Inside of this method I got a Firestore read which I require either with one or two .whereField() options. Is there a way to have the method omit the 2nd .whereField() option without having to write a 2nd version of the whole Firestore read part with?

I was thinking of something like having the .whereField() option inside of a variable which I can then just set to "" or something similar?

func loadQuestions(isAnsweredByA: Bool?, isAnsweredByB: Bool?, userB_UID: String, passOnMethod: @escaping (_ Questions: [Question]) -> () ) {

    ///Loading of stored questions of userA  (myUserUID! and userB: (userB_UID)
    var storedQuestions: [Question] = []
    listeners.append(
        db.collection(K.FStore.collectionOfRegisteredUsersName)
            .document(myUserUID!)
            .collection(K.FStore.collectionOfFriendsName)
            .document(userB_UID)
            .collection(K.FStore.collectionOfUserAnswersName)
            .whereField(K.FStore.QnA.isAnsweredByA, isEqualTo: isAnsweredByA!) //I would like this and the next line to be optional
            .whereField(K.FStore.QnA.isAnsweredByB, isEqualTo: isAnsweredByB!)
            .limit(to: 30)
            .addSnapshotListener { (querySnapshot, error) in
                if let error = error {
                    print("E: \(error)")
                } else {
                    if let snaphotDocuments = querySnapshot?.documents {
                        for document in snaphotDocuments {
                            let data = document.data()
                            let documentID = document.documentID
                            if let text = data[K.FStore.QnA.text] as? String, let topic = data[K.FStore.QnA.topic] as? String {
                                Questions.append(Question(questionID: documentID, text: text, topic: topic))
                            }
                        }
                        ///Passing on the following stored questions:
                        passOnMethod(Questions)
                    }
                }
    })
}
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Marco Boerner
  • 1,243
  • 1
  • 11
  • 34
  • You can use the pattern described in the duplicate. Even though the code is JS, the same strategy applies here. You have no obligation to chain all the conditions together into one long statement - you can add the filters conditionally to build the query. – Doug Stevenson Apr 08 '20 at 19:07
  • Thanks Doug! It took me a while to get the Swift version of this. It seems it's slightly different as I first had to create a reference and then add the query to the reference. But now it works great! Thanks! – Marco Boerner Apr 09 '20 at 10:38

0 Answers0