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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, it worked with a little adjustment. I needed to just use "self.whichQuestion" instead of "whichQuestionString" in the ArrayRemove.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.