catch let error as LocksmithError{
print(error)// it would print the case of the error.
}
但是如果我这样做
catch LocksmithError.Duplicate{
}
catch{
print (LocksmithError) // Obviously I would just print LocksmithError, it won't print the case
print (LocksmithError.rawValue) // prints nothing
}
我的问题是:使用第二种方法是否有任何我可以实际检索的方法以及错误的值/大小写?或者,如果我没有在入口点(即捕获点)获得正确的值(value),那么我就会错过这样做的机会!
最佳答案
catch
block 是排他性的,按顺序求值。当匹配成功时,我们停止。
那么,让我们考虑一下这个结构:
catch LocksmithError.Duplicate {
// 1
print("duplicate")
}
catch {
// 2
print(error)
}
如果我们在 1,则范围内的是 LocksmithError.Duplicate
。
如果我们在 2,那么在范围内的是每一种被捕获的其他错误。您无法在此处获取 LocksmithError.Duplicate
,因为ex hypothesi 它会在 1 中被捕获,而我们不会在这里。
现在,我会这样做:
catch let err as LocksmithError {
// 1
print(err)
}
catch {
// 2
print(error)
}
这可能就是您所追求的;它为我们提供了一个值 err
,它将错误带入 1 中的花括号中。 (自动 error
值仅存在于最终的 catch-all catch
block 中。)
关于swift - 如何在捕获中打印错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40183711/