I'm trying to explore this new (for me) language, and I'm making an app that like many others retrieve some json data from a server. in this function (from a tutorial I found) I get 4 errors, and I'm unable to fix it:
我正在尝试探索这种新的(对我而言)语言,而我正在制作一个应用程序,就像许多其他人从服务器中检索一些json数据一样。在这个函数中(从我发现的教程)我得到4个错误,我无法解决它:
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
}
}
the first one is at the "try", xcode suggest me to fix it using "try;" the others at the "catch" and are this others:
第一个是“尝试”,xcode建议我使用“try”修复它“抓住”中的其他人是其他人:
- Braced block of statement is an unused closure
- 声明的声明块是未使用的闭包
- Type of expression is ambiguous without more context
- 如果没有更多的上下文,表达的类型是不明确的
- Expected while in do-while-loop
- 在do-while-loop期间预期
please help me to understand
请帮我理解
1 个解决方案
#1
0
It seems that you are using Xcode 6.x and Swift 1.x where the do-try-catch
syntax is not available (only Xcode 7 and Swift 2)
您似乎正在使用Xcode 6.x和Swift 1.x,其中do-try-catch语法不可用(仅Xcode 7和Swift 2)
This code has equivalent behavior:
此代码具有等效行为:
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
}
Note: as of Xcode 7 beta 6 you can also use try?
which returns nil
if an error occurs.
注意:从Xcode 7 beta 6开始你还可以试试吗?如果发生错误,则返回nil。
#1
0
It seems that you are using Xcode 6.x and Swift 1.x where the do-try-catch
syntax is not available (only Xcode 7 and Swift 2)
您似乎正在使用Xcode 6.x和Swift 1.x,其中do-try-catch语法不可用(仅Xcode 7和Swift 2)
This code has equivalent behavior:
此代码具有等效行为:
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
}
Note: as of Xcode 7 beta 6 you can also use try?
which returns nil
if an error occurs.
注意:从Xcode 7 beta 6开始你还可以试试吗?如果发生错误,则返回nil。