当我调用的函数使用以下内容时,我经常收到这些错误:
optionalVar!
"Unexpectedly found nil while unwrapping an Optional"
如果我不能始终控制内部代码,我不确定如何处理有时会失败的函数?
有没有办法避免此类崩溃?在大多数语言中,我可以在大多数事情上放置 try catch。
当我做类似的事情时:
if let result = Blah.someExternalFunction(html: "some bad html") { }
即使在尝试添加 try? 后,这仍然可能在“someExternalFunction”内失败。在它前面。
谢谢
最佳答案
您要寻找的是if let
如果您有一个可选值,您可以简单地执行以下操作来“尝试”它:
if let val = optionalVar{
//val is already unwrapped
}
else{//it was nil}
另一种选择是使用 guard
语句。其工作原理类似。
guard let val = optionalVar
else{
//the value is nil, so you need to exit the current function
return
}
//'val' is now unwrapped for any code below the guard-else statement
关于swift - 如何包装函数 try catch 以便强制展开 nil 不会使应用程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50594590/