以适当的索引更新字典中的值

时间:2017-11-22 05:38:53

标签: ios swift nsdictionary

我有一个包含密钥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

2 个答案:

答案 0 :(得分:0)

为什么不使用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)

答案 1 :(得分:0)

这是固定的......

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

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

    }

然后声明了一个公共的int变量,index1的{​​{1}}的值被分配给该变量,而该变量又被传递给我的字典数组,就像这样......

0

然后,

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

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