在swift中将AnyObject转换为Dictionary

dpb*_*ler 44 dictionary swift

我从带有AFNetworking的iTunes API获取数据,我想创建一个包含响应的字典,但我不能这样做.

错误:无法将表达式的类型"Dictionary"转换为"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)
            })

    }
Run Code Online (Sandbox Code Playgroud)

Nat*_*ook 114

Dictionary在Swift中定义a时,您还必须提供键和值类型.就像是:

var jsonResult = responseObject as Dictionary<String, AnyObject>
Run Code Online (Sandbox Code Playgroud)

但是,如果转换失败,您将收到运行时错误 - 您最好使用以下内容:

if let jsonResult = responseObject as? Dictionary<String, AnyObject> {
    // do whatever with jsonResult
}
Run Code Online (Sandbox Code Playgroud)

  • 您不能将任何值赋给jsonResult,因为`let`关键字将其标记为不可变.您将不得不使用新的复制对象. (2认同)