AnyObject(来自JSONObjectWithData)不能转换为[String:Any] [英] AnyObject (from JSONObjectWithData) is not convertible to [String : Any]

查看:339
本文介绍了AnyObject(来自JSONObjectWithData)不能转换为[String:Any]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从使用[String:AnyObject]字典转换为使用[String:Any],希望能够在字典值(而不是旧基础)中利用本机Swift值类型(例如String)例如NSString)。这似乎几乎无处不在,但是我想要实现的这一行代码是:

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)

Swift返回一个 AnyObject!,当我使用println在控制台中显示时,它看起来完全一样,而调试区域的长签名表明NSDictionary是基础,但是,当我尝试以作为[String:Any] 在上面的行结尾进行转换时,我会收到以下错误:

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不能转换为[String:Any]

为什么会这样,我可以解决它,请记住,我想在这里使用[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.

推荐答案

在Playgro中尝试了一下und,下面的代码似乎工作。请注意, Any 不起作用,而 AnyObject 似乎按预期工作。

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

这篇关于AnyObject(来自JSONObjectWithData)不能转换为[String:Any]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆