Swift 不处理从这里抛出的错误
Swift Errors Thrown from here are not handled
我的代码在 Xcode 6 中工作,但自从我得到 Xcode 7 后,我不知道如何解决这个问题。 let jsonresult 行有一个错误,表示未处理从此处抛出的错误。代码如下:
func connectionDidFinishLoading(connection: NSURLConnection!) {
let jsonresult:NSDictionary = try NSJSONSerialization.JSONObjectWithData(self.bytes, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
print(jsonresult)
let number:Int = jsonresult["count"] as! Int
print(number)
numberElements = number
let results: NSDictionary = jsonresult["results"] as! NSDictionary
let collection1: NSArray = results["collection1"] as! NSArray
谢谢
如果您查看 swift 2 中 JSONObjectWithData
方法的定义,它会抛出错误。
class func JSONObjectWithData(data: NSData, options opt: NSJSONReadingOptions) throws -> AnyObject
在 swift 2 如果某个函数抛出错误你必须用 do-try-catch 块处理它
这是它的工作原理
func connectionDidFinishLoading(connection: NSURLConnection!) {
do {
let jsonresult:NSDictionary = try NSJSONSerialization.JSONObjectWithData(self.bytes, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
print(jsonresult)
let number:Int = jsonresult["count"] as! Int
print(number)
numberElements = number
let results: NSDictionary = jsonresult["results"] as! NSDictionary
let collection1: NSArray = results["collection1"] as! NSArray
} catch {
// handle error
}
}
或者如果您不想处理错误,您可以使用 try!
关键字强制它。
let jsonresult:NSDictionary = try! NSJSONSerialization.JSONObjectWithData(self.bytes, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
print(jsonresult)
与其他以 !这是一个冒险的操作。如果出现错误,您的程序将崩溃。
我的代码在 Xcode 6 中工作,但自从我得到 Xcode 7 后,我不知道如何解决这个问题。 let jsonresult 行有一个错误,表示未处理从此处抛出的错误。代码如下:
func connectionDidFinishLoading(connection: NSURLConnection!) {
let jsonresult:NSDictionary = try NSJSONSerialization.JSONObjectWithData(self.bytes, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
print(jsonresult)
let number:Int = jsonresult["count"] as! Int
print(number)
numberElements = number
let results: NSDictionary = jsonresult["results"] as! NSDictionary
let collection1: NSArray = results["collection1"] as! NSArray
谢谢
如果您查看 swift 2 中 JSONObjectWithData
方法的定义,它会抛出错误。
class func JSONObjectWithData(data: NSData, options opt: NSJSONReadingOptions) throws -> AnyObject
在 swift 2 如果某个函数抛出错误你必须用 do-try-catch 块处理它
这是它的工作原理
func connectionDidFinishLoading(connection: NSURLConnection!) {
do {
let jsonresult:NSDictionary = try NSJSONSerialization.JSONObjectWithData(self.bytes, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
print(jsonresult)
let number:Int = jsonresult["count"] as! Int
print(number)
numberElements = number
let results: NSDictionary = jsonresult["results"] as! NSDictionary
let collection1: NSArray = results["collection1"] as! NSArray
} catch {
// handle error
}
}
或者如果您不想处理错误,您可以使用 try!
关键字强制它。
let jsonresult:NSDictionary = try! NSJSONSerialization.JSONObjectWithData(self.bytes, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
print(jsonresult)
与其他以 !这是一个冒险的操作。如果出现错误,您的程序将崩溃。