【问题标题】:Can you append a string to a Firebase array with swift你能用 swift 将字符串附加到 Firebase 数组吗
【发布时间】:2019-12-31 01:48:00
【问题描述】:

我正在跟踪用户是否喜欢 firebase 中的餐厅,但我目前正在使用字符串来执行此操作。我知道可以在 Firebase 中更新一个数组,但是从我读过的内容来看,为了做到这一点,每次你想添加一个新元素时,你都需要重写整个数组。有没有办法只将字符串附加到数组的末尾?如果这不可能,有没有人知道一个更好的选择,然后只使用一个字符串?

这是我现在正在使用的:

var likedBarsGlobal: [String] = [] {
    didSet {
        var lb = ""
        for i in 1...likedBarsGlobal.count - 1 {
            if(i == likedBarsGlobal.count - 1){
                lb += "\(likedBarsGlobal[i])"
            } else {
                lb += "\(likedBarsGlobal[i]), "
            }
        }

        db.collection("users").document(userId).updateData(["likedBars": lb ]) { (error) in
            if error != nil {
                print(error)
            }
        }
    }
}

【问题讨论】:

    标签: ios arrays swift firebase google-cloud-firestore


    【解决方案1】:

    Firestore 有一个特殊的 documented operation 可以使用 FieldValue.arrayUnion() 将单个项目附加到数组的末尾:

    let washingtonRef = db.collection("cities").document("DC")
    
    // Atomically add a new region to the "regions" array field.
    washingtonRef.updateData([
        "regions": FieldValue.arrayUnion(["greater_virginia"])
    ])
    

    如果您想对数组进行任何更改而不是添加或删除单个项目,则必须读取数组,修改它,然后将其写回。

    【讨论】:

    • 这应该有 3 个以上的赞成票。我在其他任何地方都没有找到这个答案,它很好地回答了这样一个需要的问题。
    猜你喜欢
    • 2016-03-02
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    相关资源
    最近更新 更多