我正在尝试将我的代码转换为Swift 2,并且我遇到了最后一个函数的问题。我在task
的声明中得到了以下错误:
Invalid conversion from throwing function of type ... to non throwing type.
func performSearch(searchTerm: String){
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(urlForQuery(searchTerm)!, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
do {
let result: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! NSDictionary
}
let results: AnyObject? = result.objectForKey("results")
if let testVar: NSMutableArray = results as? NSMutableArray {
// Uncomment this to print all feeds
//println(testVar)
self.searchedPodcasts.removeAllObjects()
self.searchedPodcasts.addObjectsFromArray(testVar as [AnyObject])
NSNotificationCenter.defaultCenter().postNotificationName("SearchPerformed", object: self)
}
})
task!.resume()
}
我尝试过以下操作,但它也不起作用,这也意味着我无法出于某种原因调用task.resume:
func performSearch(searchTerm: String){
let session = NSURLSession.sharedSession()
do {
let task = session.dataTaskWithURL(urlForQuery(searchTerm)!, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
do {
let result: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! NSDictionary
}
let results: AnyObject? = result.objectForKey("results")
if let testVar: NSMutableArray = results as? NSMutableArray {
// Uncomment this to print all feeds
//println(testVar)
self.searchedPodcasts.removeAllObjects()
self.searchedPodcasts.addObjectsFromArray(testVar as [AnyObject])
NSNotificationCenter.defaultCenter().postNotificationName("SearchPerformed", object: self)
}
})
} catch {
print("error)
}
task!.resume()
}
我该怎么做才能解决它?
编辑:试过这个,但仍然返回相同的错误。
func test(searchTerm: String) {
let session = NSURLSession.sharedSession()
do {
let task = try session.dataTaskWithURL(urlForQuery(searchTerm)!, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
let result: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! NSDictionary
})
} catch {
print("hello")
}
}
答案 0 :(得分:3)
尝试在do-try-catch
句中添加一个catch块:
do {
let result: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! NSDictionary
}
catch {
print("error");
}
您还需要在外部声明result
变量或在do
块中移动更多代码。
有关Swift 2 check out this guide中的异常处理的更多信息。
答案 1 :(得分:1)
Apple在Swift 2中用ErrorType替换了NSError。
因此,用ErrorType替换你自己对NSError的显式使用,你不需要在另一个答案中建议的额外的try catch块,你可以用更少的代码表达你的错误处理。