SwiftUI Firebase - Add or Subtract Integers in Firebase

Viewed 214

I am trying to create a like feature in SwiftUI using Firebase. However, the code I already have only sets the number in Firebase to 1 or -1, and doesn't actually add or subtract the number. My goal is for addLike to add 1 to the number, and unLike to subtract 1 from the number.

func addLike(id: String){
        ref.collection("Posts").document(id).updateData(["likes": +1]) { (err) in //sets DB to +1, figure out how to add
            if err != nil{
                print(err!.localizedDescription)
                return
            }
        }
    }
    
    func unLike(id: String){
        ref.collection("Posts").document(id).updateData(["likes": -1]) { (err) in //sets DB to -1, figure out how to add
            if err != nil{
                print(err!.localizedDescription)
                return
            }
        }
    }

Sorry if this is a simple solution. I've tried everything - even a previous post, which didn't get answered properly, so I refined this post into just one question.

Thanks!

1 Answers

What you're looking for is the increment operator that Firestore has.

You can use it to increment/decrement a value, without having to use a transaction like this:

ref.collection("Posts").document(id).updateData(["likes": FieldValue.increment(Int64(1))])

ref.collection("Posts").document(id).updateData(["likes": FieldValue.increment(Int64(-1))])
Related