swift 中的 do catch 语句错误
Errors in do catch statement in swift
我正在尝试探索这种新的(对我来说)语言,并且我正在制作一个与许多其他应用程序一样的应用程序,从服务器检索一些 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
}
}
第一个在 "try",xcode 建议我使用 "try;" 修复它
"catch" 的其他人,这是其他人吗:
- 括号语句块是未使用的闭包
- 表达式类型不明确,没有更多上下文
- 预期在 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?
其中 returns nil
。
我正在尝试探索这种新的(对我来说)语言,并且我正在制作一个与许多其他应用程序一样的应用程序,从服务器检索一些 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
}
}
第一个在 "try",xcode 建议我使用 "try;" 修复它 "catch" 的其他人,这是其他人吗:
- 括号语句块是未使用的闭包
- 表达式类型不明确,没有更多上下文
- 预期在 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?
其中 returns nil
。