Ignatius_Gim Ignatius_Gim - 5 months ago 26
Swift Question

Casting an AnyObject to a Dictionary nested in an Array

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?

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


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] {

Or if you want to be more concise...

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