我在swift3中感到困惑的错误处理。我尝试做类似“如果XX函数出错,然后尝试YY函数”
让我向您展示我的尝试:
class MyClass {
enum error: Error
{
case nilString
}
func findURL() {
do {
let opt = try HTTP.GET(url_adr!)
opt.start { response in
if let err = response.error {
print("error: \(err.localizedDescription)")
return //also notify app of failure as needed
}
do
{
/* This is func1. and got error. I want to if this function has error then go next function. */
try self.stringOperation(data: response.description)
}
catch{
print("doesn't work on func1. trying 2nd func")
self.stringOperation2(data:response.descritption)
}
}
} catch let error {
print("got an error creating the request: \(error)")
}
}
func stringOperation(data:String)throws -> Bool{
do{
/** 1 **/
if let _:String = try! data.substring(from: data.index(of: "var sources2")!){
print("its done")
}else{
throw error.nilString
}
IN 1:我在此行中收到此致命错误:
“致命错误:解开可选值时意外发现nil”,程序崩溃。
我用Google搜索错误处理尝试理解并应用到我的代码中。但是还没有成功。有人可以解释我在哪里错了吗?
附加信息:我为.substring(from:...)和.index(of:“str”)获得了字符串扩展名。因此,这些行不会让您感到困惑。
最佳答案
作为一般规则,请尝试避免在存在以下情况时使用强制展开(!)
if let _: String= try! data.substring...
改为使用
if let index = data.index(of: "var sources2"),
let _: String = try? data.substring(from: index) { ... } else { ... }
这样,您就消除了可能导致崩溃的两个力解开。您已经具有用于捕获nil值的
if let
保护,因此可以通过使用条件展开来充分利用它。关于swift - 在Swift 3中对错误处理感到困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44997216/