Sai Kumar
Sai Kumar

Reputation: 67

Update the values which is in array of dictionary

I have my array of dictionary like below:

var ArrayOfData: [[String: Any]] = []

ArrayOfData = [["ID": 18, "Data": <null>, "avgScore": 0],["ID": 8, "Data": <null>, "avgScore": 0],["ID": 9, "Data": <null>, "avgScore": 0]]

My ArrayOfData has the above values. But I need to update the particular object dictionary values based on my id.

I tried like below but I don't know how I can update the values.

for datas in ArrayOfData {
    var gameIdData = datas["ID"] as? Int
    if gameIdData == "18" {
        var gameData = datas
        gameData["avgScore"] ="123"
    }
}

I need to update my particular id object and again I need to append to my new array of dictionary or old array of dictionary.

My updated values should be like below:

var UpdatedArrayOfData: [[String: Any]] = []

ArrayOfData = [["ID": 18, "Data": <null>, "avgScore": 123],["ID": 8, "Data": <null>, "avgScore": 0],["ID": 9, "Data": <null>, "avgScore": 0]]

How can I achieve that?

Upvotes: 0

Views: 174

Answers (1)

Jag
Jag

Reputation: 987

for index in ArrayOfData.indices {
if let gameId = ArrayOfData[index] ["ID"] as? Int {
    if gameId == 18 {
        ArrayOfData[index] ["avgScore"] = 123
    }
}

Use the index of the array to update the specific object.

Upvotes: 1

Related Questions