用swift向字典中插入任何对象

时间:2021-07-20 16:10:03

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.

我用AFNetworking从iTunes API获取数据,我想用响应创建一个字典,但我做不到。

Error: Cannot convert the expression's type "Dictionary " to type "Hashable"

错误:无法将表达式的类型“Dictionary”转换为“Hashable”

This is my code:

这是我的代码:

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)
            })

    }

1 个解决方案

#1


106  

When you define a Dictionary in Swift you have to give key and value types as well. Something like:

在Swift中定义字典时,还必须提供键和值类型。喜欢的东西:

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
}

#1


106  

When you define a Dictionary in Swift you have to give key and value types as well. Something like:

在Swift中定义字典时,还必须提供键和值类型。喜欢的东西:

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
}