在字典中为键分配值时出现问题

时间:2017-11-10 05:56:13

标签: 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并将结果值分配给键sellingPrice

因此,在这种情况下,将从200的第一个remaining_balance中减去50,以将第一个字典的partial amount的值设为150.因为现在没有剩下的{{1因为它已被完全用完了,所以第二个remaining_balance的{​​{1}}的值将为200.所以第一个sellingPrice将为150&第二个remaining_balance将是200。

这是我到目前为止所尝试的...但它似乎无法正常工作......

remaining_balance

3 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:0)

试试这个解决方案:

var partialAmount = 50

arrayOfDictionary =  arrayOfDictionary.map { (dict) -> [String:Any] in
    var mutableDict : [String:Any] = dict
    if let sellingPrice = dict["sellingPrice"] as? String{
        if partialAmount < Int(sellingPrice)!{
            let remainingBalance = Int(sellingPrice)! - partialAmount
            partialAmount -= partialAmount
            mutableDict["remaining_balance"] = "\(remainingBalance)"
            return mutableDict
        }
        return dict
    }
    return dict
}

答案 2 :(得分:0)

请提及字典的密钥类型。

let array:[Dictionary<String,Any>] = [["sellingPrice" : "200"],
                 ["sellingPrice" : "200"]]