SwiftUI Firebase - 在 Firebase 中添加或减去整数

Posted

技术标签:

【中文标题】SwiftUI Firebase - 在 Firebase 中添加或减去整数【英文标题】:SwiftUI Firebase - Add or Subtract Integers in Firebase 【发布时间】:2021-06-28 02:05:50 【问题描述】:

我正在尝试使用 Firebase 在 SwiftUI 中创建类似的功能。但是,我已经拥有的代码仅将 Firebase 中的数字设置为 1 或 -1,实际上并没有添加或减去该数字。我的目标是 addLike 将数字加 1,unLike 将数字减 1。

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
            
        
    

抱歉,这是一个简单的解决方案。我已经尝试了所有方法 - 甚至是以前的帖子,但没有得到正确回答,因此我将这篇帖子改进为一个问题。

谢谢!

【问题讨论】:

【参考方案1】:

您正在寻找的是 Firestore 拥有的 increment operator。

您可以使用它来增加/减少一个值,而不必使用这样的事务:

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

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

【讨论】:

以上是关于SwiftUI Firebase - 在 Firebase 中添加或减去整数的主要内容,如果未能解决你的问题,请参考以下文章

如何修复:“@angular/fire”'没有导出成员 'AngularFireModule'.ts(2305) ionic、firebase、angular

node_modules/@angular/fire/firebase.app.module.d.ts 中的错误?

如果超时或无法访问服务器,Fire base 不会调用 onCancelled

如何在 Fire Base 中使用完成处理程序

Fire Storage Exception([firebase_storage/unauthorized] 用户无权执行所需的操作。)(我的规则是允许读/写)

SwiftUI - 在 Firebase 上更新密码