快速将AnyObject投射到字典 [英] Casting AnyObject to Dictionary in swift
本文介绍了快速将AnyObject投射到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用AFNetworking从iTunes API获取数据,我想使用响应创建一个Dictionary,但是我做不到.
I'm getting data from iTunes API with AFNetworking and I want to create a Dictionary with the response but I can't do it.
错误:无法将表达式的类型字典"转换为类型哈希"
Error: Cannot convert the expression's type "Dictionary " to type "Hashable"
这是我的代码:
func getItunesStore() {
self.manager.GET( "https://itunes.apple.com/es/rss/topfreeapplications/limit=10/json",
parameters: nil,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
var jsonResult: Dictionary = responseObject as Dictionary
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
println("Error:" + error.localizedDescription)
})
}
推荐答案
在Swift中定义Dictionary
时,还必须提供键和值类型.像这样:
When you define a Dictionary
in Swift you have to give key and value types as well. Something like:
var jsonResult = responseObject as Dictionary<String, AnyObject>
但是,如果强制转换失败,则会出现运行时错误-最好使用以下内容:
If the cast fails, however, you'll get a runtime error -- you're better off with something like:
if let jsonResult = responseObject as? Dictionary<String, AnyObject> {
// do whatever with jsonResult
}
这篇关于快速将AnyObject投射到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文