Swathi
Swathi

Reputation: 31

how to append an array of dictionaries to another array

I tried to append an array of dictionaries which are coming from server to a globally declared array.but i am getting an error like "Cannot convert value of type '[Any]' to expected argument type '[String : Any]'"if anyone helps me would be great.Thanks in advance

var pro = [[String:Any]]()

    var productsdetails = Array<Any>()
    productsdetails = userdata.value(forKey: "products") as! Array
     print("response\(productsdetails)")
               self.pro = self.pro.append(productsdetails)
                    print(self.pro)

Upvotes: 0

Views: 301

Answers (4)

Uzair Dhada
Uzair Dhada

Reputation: 333

Can you show us your response which has key products? As there is mismatch with the variable pro and productdetails. As i see pro holds values as "Array of Dictionary with key as String type and Value as Any type" which again has Array above it and productdetails is expecting Array of Any type not the Array of Dictionary Type. Assuming your products has Array of String Type or can be even a class object type you can do it as below.

var pro = Array<Any>() //Or You can make Array<String>() or Array<CustomClass>()

var userdata:[String:[String]] = ["products":["One","Two","Three"]]

var productsdetails = Array<Any>()
productsdetails = userdata["products"] ?? []
print("response\(productsdetails)")
pro.append(productsdetails)

Upvotes: 0

Jamil Hasnine Tamim
Jamil Hasnine Tamim

Reputation: 4448

You can try this: (Swift-4.2)

var data: [String: Any] = [
    "key1": "example value 1",
    "key2": "example value 2",
    "items": []
]

for index in 1...3 {

    let item: [String: Any] = [
        "key": "new value"
    ]

    // get existing items, or create new array if doesn't exist
    var existingItems = data["items"] as? [[String: Any]] ?? [[String: Any]]()

    // append the item
    existingItems.append(item)

    // replace back into `data`
    data["items"] = existingItems
}

Answer same as: Append to array in [String: Any] dictionary structure

Upvotes: 0

Ankur Lahiry
Ankur Lahiry

Reputation: 2315

Here pro is appending a new element [String : String]

to solve this iterate

var pro = [[String:Any]]()

if let productsdetails = userdata.value(forKey: "products") as? [[String: Any]] {
    for details in productsdetails {
       pro.append(details)
    }

}

or you may use directly self.pro = productsdetails if you not to want iterate

**image shows [String : String] as I have used [String : String] instead of [String : Any]*

Upvotes: 0

Pradip Patel
Pradip Patel

Reputation: 348

Use this code like below, i hope this works

var pro = [[String:Any]]()

if let productsdetails = userdata.value(forKey: "products") as? [[String:Any]] {
    print("response\(productsdetails)")
    self.pro.append(productsdetails)
    print(self.pro)
}

Upvotes: 1

Related Questions