Tom Hawley
Tom Hawley

Reputation: 555

AnyObject (from JSONObjectWithData) is not convertible to [String : Any]

I moved from using a [String : AnyObject] dictionary to using a [String : Any] in the hope of being able to take advantage of native Swift value types (e.g String) in the dictionary values rather than old foundation ones (e.g. NSString). This seems to have worked almost everywhere, however at the very source of what i'm trying to achieve is this line of code:

let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)

In Swift this returns an AnyObject!, which looks exactly as expected when i use println to show it in the console, and the long signature in the debug area suggests an NSDictionary underlies it, however when I try to cast this with as [String : Any] at the end of the above line I get the following error:

AnyObject is not convertible to [String : Any]

Why would this happen, and how can I fix it, bearing in mind I do want to use [String : Any] here, and can't see any good reason it shouldn't be possible, and a good solution.

Upvotes: 1

Views: 3397

Answers (1)

Mundi
Mundi

Reputation: 80265

After experimenting a bit in Playground, the code below seems to work. Note that Any does not work, while AnyObject seems to work as expected.

let jsonString = "{\"name\":\"John\", \"age\":23}"
let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
let json = NSJSONSerialization.JSONObjectWithData(jsonData, 
   options: NSJSONReadingOptions.MutableContainers, error: nil) as [String:AnyObject]
// ["name": "John", "age": __NSCFNumber]
let name = json["name"] as AnyObject! as String  // "John"
let age  = json["age"]  as AnyObject! as Int     // 23

Upvotes: 3

Related Questions