通用参数'Key'无法推断Swift 2

时间:2016-01-16 19:17:14

标签: swift2 ios9 xcode7

我是swift 2的初学者,我没有发现问题。错误在这一行:

let jsonDictionary try NSJSONSerialization.JSONObjectWithData = (data!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary
func searchItunesFor(searchTerm: String) {
    let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
    let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
    let urlPath: String = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=software"
    let url: NSURL = NSURL(string: urlPath)!
    let session = NSURLSession.sharedSession()
    session.dataTaskWithURL(url, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        do {
            if let ipString = NSString(data:data!, encoding:NSUTF8StringEncoding){
                let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary

                let results: NSArray = jsonDictionary["results"] as NSArray
                dispatch_async(dispatch_get_main_queue(), {
                    self.tableData = results
                    self.appsTableView?.reloadData()
                })
            }
        }catch{
            print("Bad ")
        }
    }).resume()

3 个答案:

答案 0 :(得分:0)

let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary

答案 1 :(得分:0)

我希望这可以帮助一些人,即使它有点晚了:

此处的问题是您尝试将JsonObject转换为Dictionary而不是NSDictionary

因此,您只需在代码中将Dictionary替换为NSDictionary即可。这应该照顾错误。

Swift 2

let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

Swift 3

let jsonDictionary = try JSONSerialization.JSONObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

答案 2 :(得分:0)

在Swift 3中为我工作的是定义字典键值类型。

if let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary<String, String>{
    // something happens here
} 

注意该行末尾的NSDictionary<String, String>

如果您的对象看起来像这样,当然:

{
    "someProp" : "some value",
    "someOtherProp" : "some other value"
}

如果您不知道自己获得的价值,可能是任何对象使用NSDictionary<String, Any>