gpt4 book ai didi

swift - 如何在捕获中打印错误

转载 作者:搜寻专家 更新时间:2023-11-01 06:37:08 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com