Reputation: 1389
I am getting a json from server. I am using following code:
self.socket.on("contactList") {data, ack in
let resultData = (data.first as! String).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let jsonResult: Dictionary = NSJSONSerialization.JSONObjectWithData(resultData!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<String, AnyObject>
let results: NSArray = jsonResult["result"] as! NSArray
for item in results {
let username = item["username"] as! String
}
}
But I am getting following compiler error:
Cannot subscript a value of type 'Element' (aka 'AnyObject') with an index of type 'String'
for this line:
let username = item["username"] as! String
How can i fix it?
I didn't get any error swift 1.2 but now I am migrating to 2.0 and I can't resolve this problem.
My xcode version is 7.0 (7A220)
Upvotes: 1
Views: 3882
Reputation: 621
I had a similar problem, try this:
let results: [String:AnyObject] = jsonResult["result"] as! [String:AnyObject]
Upvotes: 0
Reputation: 4186
I suppose results
is the array of dictionaries. Then:
let results = jsonResult["result"] as! [[String: AnyObject]]
Of course, I would recommend to safely unwrap everything instead of using forced unwrapping to avoid crashes. What would happen if network error occurs? (crash)
Upvotes: 1
Reputation: 182
You have to cast item to Dictionary before.
if let dic = item as Dictionary {
let username = dic["username"] as! String
}
Upvotes: 0
Reputation: 299623
item
is an AnyObject
. That's not a dictionary and you can't subscript it. Following your style, you probably mean:
// Results are expected to be an array of dictionaries of string->string
let results = jsonResult["result"] as! [[String:String]]
for item in results {
let username = item["username"]
}
But note that this is incredibly dangerous code. If the server sends you anything you don't expect, your program will crash. You really need to unload this data more carefully with as?
to make sure along the way that you got what you think you go. Then load that data into a custom struct
type so you don't have to test it in the rest of the program.
Upvotes: 0