0

I have this code here and I want to delete certain value inside the array "Answered". Is there a simple way to access the first value in the array? This is right but shows what I want to happen "Answered[0]" <- I want to get the first value in that array and delete it. Thank you in Advance

let uid = Auth.auth().currentUser?.uid
            print(self.randomArray)
          let wash = db.collection("users").document(uid!)
          wash.updateData([
            "Answered": FieldValue.arrayUnion([self.randomArray])
              ])
          }
            if(self.check.isEmpty != true){
                self.whichQuestion = self.check[0]
                self.whichQuestionString = String(self.whichQuestion)
                db.collection("users").document(uid!).updateData([
                    "Answered": FieldValue.delete(),
                ]) { err in
                    if let err = err {
                        print("Error updating document: \(err)")
                    } else {
                        print("Document successfully updated")
                    }
                }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Captain Dilan
  • 71
  • 1
  • 6

1 Answers1

2

If your array contains unique values however, you can remove the item with:

self.whichQuestionString = String(self.whichQuestion)
db.collection("users").document(uid!).updateData([
    "regions": FieldValue.arrayRemove([whichQuestionString])
])

If you only know the index of the item, there is no way to remove it without knowing the entire array.

The recipe for this is:

  1. Read the document from Firestore
  2. Modify the array in your application code
  3. Write the entire modified array back to Firestore

Also see (none of which unfortunately are for Swift):

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you very much, it worked with a little adjustment. I needed to just use "self.whichQuestion" instead of "whichQuestionString" in the ArrayRemove. – Captain Dilan Apr 11 '20 at 14:33