Subso
Subso

Reputation: 1443

Swift - Update an array of NSDictionary with values from another NSDictionary

Basically, I have an NSarray of dictionaries coming as a JSON response only once when view appears. Now, I need to update a particular value of a key in those dictionaries with another set of dictionary coming separately in every few second such that I can update my array of dictionaries continuously with those values and show some realtime set of data on the screen.

Example: This is the array of dictionary I am getting from backend

[
  {item_id: 1001, name: "Apple", current_price: "$10"},
  {item_id: 1009, name: "Orange", current_price: "$15"},
  {item_id: 1004, name: "Mango", current_price: "$5"}
]

Current price is something which varies continuously, whose data I am receiving in NSDictionary format separately.

["1009": "$16", "1004": "$3", "1001": "$11"]

As you can see the new NSDictionary is mapped with the item_id to the current price value.

I need a way out to make sure the current price gets updated from this NSDictionary to the array of dictionary so that I can reuse that array to reload my UITableview and show the updated realtime price.

Upvotes: 1

Views: 1628

Answers (1)

Vladyslav Zavalykhatko
Vladyslav Zavalykhatko

Reputation: 17364

You can do it like this:

let items = [["item_id": 1001, "name": "Apple", "current_price": "$10"], ["item_id": 1009, "name": "Orange", "current_price": "$15"], ["item_id": 1004, "name": "Mango", "current_price": "$5"]]

let prices = ["1009": "$16", "1004": "$3", "1001": "$11"]

let updatedItems = items.map { itemDict -> [String: Any] in
    var updatedItem = itemDict
    if let idKey = itemDict["item_id"] as? Int {
        prices["\(idKey)"].flatMap { updatedItem["current_price"] = $0 }
    }
    return updatedItem
}

Upvotes: 2

Related Questions