0

I'm getting an Object from API response which looks something like below.

"Home":[
{
"type":"Something",
"id":"Something",
"interval":3,
"category":"Something",
"title":"Something",
"vc":[]
},
{
"type":"Something",
"id":"Something",
"TableFooterDisclaimer":"",
"category":"Something",
"title":"Something",
"vc":[
{
"Something":"Something",
"id":0,
"Something":"Something",
"Something":"Something",
"Something":"Something",
"Something":"Something",
"Something":"Something",
},
{
"Something":"Something",
"id":1,
"Something":"Something",
"Something":"Something",
"Something":"Something",
"Something":"Something",
"Something":"Something",
},
{
"Something":"Something",
"id":2,
"Something":"Something",
"Something":"Something",
"Something":"Something",
"Something":"Something",
"Something":"Something",
}
]
},

I'm trying to insert one more record which looks like below.

let object : [String : Any] = [
"Something":"Something",
"id":1,
"Something":"Something",
"Something":"Something",
"Something":"Something",
"Something":"Something",
"Something":"Something",
]

This object I'm trying to insert inside vc array of the 1st index of Home, like below but getting issues.

if let serverArray = info["Home"] as? [[String: AnyObject]] {
     self.myArray = serverArray
     self.myArray![1]["vc"]?.insert(self.object, at: 0)
}

I have tried converting let object : [String:Any] to [String:AnyObject] but that also didn't work.

7
  • did you try [String : String]? Commented Oct 15, 2020 at 12:00
  • It won't be [String: String], I have just updated the snippets. Commented Oct 15, 2020 at 12:03
  • At which part do you have issue? serverArray has value and adding the object fails? Commented Oct 15, 2020 at 12:03
  • 1
    Have you considered creating a struct/structs and decode your data using Codable? Commented Oct 15, 2020 at 12:04
  • @gcharita Just asking, the way I'm trying to insert is correct ?? Commented Oct 15, 2020 at 12:05

1 Answer 1

1

You can try something like this:

if var serverArray = info["Home"] as? [[String: Any]] {
    if serverArray.count > 1 {
        var vcs = serverArray[1]["vc"] as? [[String: Any]]
        vcs?.insert(self.object, at: 0)
        serverArray[1]["vc"] = vcs
    }
    self.myArray = serverArray
}

But it's a little ugly.

Using Codable and JSONDecoder like @JoakimDanielson commented will be better.

Sign up to request clarification or add additional context in comments.

2 Comments

I had to make some changes to the above solution but thanks for the suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.