0
votes

I am looking to cast an AnyObject variable as a Dictionary nested in an Array. For example, I declare the variable in my function:

var items: [[String:String]] = [
     [
         "pid": "1",
         "content": "123",
         "vote": "1",
         "city": "New York",
         "country": "United States"
     ]
 ]

Then I fetch a JSON object from an HTTP request and convert it into an AnyObject. Then I am trying to append the data fetched by the HTTP request as an AnyObject onto the original variable.

This process fails at the casting of the AnyObject into the desired [[String: String]] form.

func updateTable(data: AnyObject?) {
    let data_array = (data as! NSArray) as! Array<Dictionary<String, String>>

    self.items += data_array
}

This function include the casting of the variable and the addition of the arrays.

How can I cast this variable correctly?

EDIT I forgot to mention that I cast my Serialized JSON Output as [AnyObject] before passing it through the function

1
Try this => let data_array = data as! NSDictionary - Chandresh
Its not compatible with with the original variable is [[String: String]] - Ignatius_Gim
Try this => data as Dictionary<String, String> - Chandresh
Also doesn't work, it says "cannot convert value of type [[String, String]] to expected argument type 'input_' - Ignatius_Gim

1 Answers

3
votes

I think you need to cast the individual elements of the array.

func updateTable(data: [AnyObject]) {
for item in data {
    if let item = item as? [String: String] {
        items.append(item)
    }
}

Or if you want to be more concise...

func updateTable(data: [AnyObject]) {
    items += data.flatMap({$0 as? [String: String]})
}