我有一个名为objects
的集合/类型为Object
的文档,其中有一个类型为ObjectNotification
的数组,我正在尝试将每个notification.read
更新为{{1 }}。
我有一个视图,可显示单个数组true
中所有对象的所有userNotifications
。
在为视图使用self.viewModel.userNotifications
时,我试图将onAppear
中的每个userNotification.read
设置为true
并更新FirestoreDB。
但是,我不确定采用哪种最佳方法,目前,我正在遍历数组并尝试更新self.viewModel.userNotifications
中的每个userNotification,然后更新数据库中的文档,该文档会将self.viewModel.objects.userNotifications
更新为会提取所有self.viewModel.userNotifications
。
但是在尝试更改结构时出现以下错误,我尝试更改self.viewModel.userNotifications
语句中的值,然后调用for in
方法来更新数据库中的文档。
无法通过下标分配:“ h”是一个“ let”常量
updateObect(object)
代替上面的方法,如何更改数据库中的字段?
答案 0 :(得分:0)
这是对实际问题的解决方案,不能解决问题的Firebase部分,因为在实际问题中未列出。
我要在这里进行一个大胆的猜测,因为问题不完整,但是我认为问题中的任何对象“ h”都是一个包含通知的数组属性的结构。
如果是这样,那么您将无法在for循环中执行此操作
h.notifications[index] = r
因为结构是 value 类型,而不是 reference 类型的类。这意味着在for循环中,对象是数组元素的副本,而不是元素本身
for copyOfArrayElement in someArrayOfStructs {}
有一些解决方案;这是两个。首先是使用索引访问实际的struct对象来遍历数组。假设我们有一个带有名称和数组属性的水果结构数组
struct FruitStruct {
var name = ""
var someList = [String]()
}
var banana = FruitStruct(name: "banana", someList: ["a", "b", "c"])
var grape = FruitStruct(name: "grape", someList: ["d", "e", "f"])
var fruitsArray = [banana, grape]
然后将每个水果名称修改为'Hello'并将someList中索引为1的元素修改为'World'的循环
for i in 0..<fruitsArray.count {
fruitsArray[i].name = "Hello"
fruitsArray[i].someList[1] = "World"
}
fruitsArray.forEach { print($0.name, $0.someList) }
和输出
Hello ["a", "World", "c"]
Hello ["c", "World", "e"]
或者将结构更改为类(作为参考),以便您可以直接使用现有循环修改属性。
class FruitClass {
var name = ""
var someList = [String]()
convenience init(withName: String, andArray: [String] ) {
self.init()
self.name = withName
self.someList = andArray
}
}