在适当的索引处更新字典中的值

Updating the value in a dictionary at the proper index

我有一本字典,它有一个关键字 product_quantity。现在 product_quantity 的值为“1”。但是后来 product_quantity 从选择器视图中获得了不同的值,那时我想要更新字典中 product_quantity 的值。换句话说,我想更新字典中的值。但是我无法弄清楚如何实现这一目标。

到目前为止已经完成了这样的事情..这里我给出的 index 只是初始化为 var index = Int() 并且它的值始终为 0。所以它不起作用。

希望有人能帮忙...

self.appDelegate.myDictionary["product_quantity"] = cell.qtyPickerField.text!

self.appDelegate.arrayOfDictionary[index] = self.appDelegate.myDictionary

为什么不使用 struct 来保存您想要的数据。

struct Product {
    var quantity: Int
}

然后创建这个结构的对象。

var product = Product(quantity: 0)

然后您只需要在程序稍后的某个时间点更新数量变量。

product.quantity = 10

更新: 刚刚看到您的编辑。

struct Product {
    var quantity: Int
}

struct MyData {
    var product: Product
    mutating func updateProduct(quantity: Int) {
        product.quantity = quantity
    }
}


var product = Product(quantity: 0)
var myData = MyData(product: product)
print(myData.product.quantity)

// call the updateProduct method to update the quantity.
myData.updateProduct(quantity: 20)
print(myData.product.quantity)

这是固定的...

tableviewcell的索引可以这样找到...

 let indexPath = self.tableview.indexPath(for: cell)
  if let index1 = indexPath {            

    }

然后声明了一个通用的 int 变量,0 处的 index1 的值被分配给该变量,然后该变量又被传递到我的字典数组中,就像这样...

 let indexPath = self.tableview.indexPath(for: cell)
      if let index1 = indexPath {            
         self.theValueOfIndex = index1[0]
    }

然后,

myDictionary["product_quantity"] = cell.qtyPickerField.text!


arrayOfDictionary[self.theValueOfIndex] = myDictionary

这更新了正确索引处的值。