swift - 为字典中的键分配值的问题

标签 swift dictionary

我有一个像这样的字典数组......

[
  {
    "sellingPrice" : "200",
    "transaction_id" : "COD",
    "shipping_charges" : "",
    "id" : "3",
    "payment_method" : "",
    "taxes" : "0",
    "applied_coupon_code" : "",
    "discount_price" : "",
    "quantity" : "13",
    "transaction_type" : "COD",
    "remaining_balance" : "",
    "grand_total" : ""
  },
  {
    "sellingPrice" : "200",
    "transaction_id" : "COD",
    "shipping_charges" : "",
    "id" : "22",
    "payment_method" : "",
    "taxes" : "0",
    "applied_coupon_code" : "",
    "discount_price" : "",
    "quantity" : "3",
    "transaction_type" : "COD",
    "remaining_balance" : "",
    "grand_total" : ""
  }
]

我有一个名为“部分金额”的东西,值为 50。现在,我想遍历字典数组,检查 partial amount 是否小于 sellingPrice,如果小于,则从中减去 partial amount,结果值将分配给键 remaining_balance

所以在这种情况下,将从 200 的第一个 sellingPrice 中减去 50,得到第一个字典的 remaining_balance 的值为 150。因为现在什么都没有了剩余的 partial amount 50 因为它已经完全用完,第二个 remaining_balancesellingPrice 的值为 200。所以第一个 remaining_balance 将为 150,第二个 remaining_balance 将为 200。

这是我到目前为止尝试过的方法..但它似乎不起作用...

for (index, dict) in self.appDelegate.arrayOfDictionary.enumerated() {
    for element in dict {                
        if element.key == "sellingPrice" {
            let PAinTxtField =  alertController.textFields?.first?.text)!
            var thePA = (Int(PAinTxtField ) ?? 0) //This is partial amount

            let theSP = (Int("\(element.value)") ?? 0) //This is selling price
            if thePA < theSP {
                self.remainingAmt = theSP - thePA
                var dictCopy = dict
                dictCopy["remaining_balance"] = "\(self.remainingAmt)" //The mistake seems to be because of this line. But cannot figure out what exactly...:(

            }
        }
    }
}

最佳答案

试试这个:

self.appDelegate.arrayOfDictionary[index] = dictCopy //replace new copyDict with old dict 

关于swift - 为字典中的键分配值的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47216495/

相关文章:

ios - '==' 如何与 UIViewControllers 一起工作?

swift - 我的滚动虽然通常很顺利,但有时会很不稳定

ios - arc4random (mac os x) 有多随机? (或者我做错了什么?)

Javascript:读取 ES6 Map.size 是常数时间吗?

ios - 如何从 Swift 中的字典中获取特定索引处的键?

objective-c - 快速扩展 objc ,初始值设定项

python - 通过 API 调用发送大字典会中断开发服务器

python - Python中的字典小写

ios - Swift:如何将字典数组添加到数组?

ios - 如何将 UIAlertController 操作表标题垂直居中对齐?