Json swift中do catch语句中的错误
我正在尝试探索这种新的(对我来说)语言,我正在制作一个应用程序,它和其他许多应用程序一样,可以从服务器检索一些json数据。 在这个函数中(从我找到的教程中),我得到了4个错误,但我无法修复它:Json swift中do catch语句中的错误,json,swift,try-catch,Json,Swift,Try Catch,我正在尝试探索这种新的(对我来说)语言,我正在制作一个应用程序,它和其他许多应用程序一样,可以从服务器检索一些json数据。 在这个函数中(从我找到的教程中),我得到了4个错误,但我无法修复它: func json_parseData(data: NSData) -> NSDictionary? { do { let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NS
func json_parseData(data: NSData) -> NSDictionary? {
do {
let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
print("[JSON] OK!")
return (json as? NSDictionary)
}catch _ {
print("[ERROR] An error has happened with parsing of json data")
return nil
}
}
第一个是在“try”,xcode建议我使用“try”来修复它
其他人在“捕获”中,这是其他人:
- 大括号语句块是未使用的闭包
- 表达式类型不明确,没有更多上下文
- 在do while循环中应为
请帮助我理解您似乎正在使用Xcode 6.x和Swift 1.x,其中的
do try catch
语法不可用(仅Xcode 7和Swift 2)
此代码具有等效的行为:
func json_parseData(data: NSData) -> NSDictionary? {
var error: NSError?
// passing the error as inout parameter
// so it can be mutated inside the function (like a pointer reference)
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainerserror: &error)
if error == nil {
print("[JSON] OK!")
return (json as? NSDictionary)
}
print("[ERROR] An error has happened with parsing of json data")
return nil
}
注意:从Xcode 7 beta 6开始,您也可以使用
try?
,如果出现错误,它将返回nil
。我假设您使用的是swift 2.0,对吗?您使用的是Xcode 6,但swift 2仅在Xcode 7中可用。